合并二叉树

  1. 输入:{1,3,2,5},{2,1,3,#,4,#,7}
  2. 返回值:{3,4,5,5,4,#,7}
  1. 解题思路:
  2. 同时递归两棵树;
  3. 考虑到节点有以下情况
  4. t1 = null, t2!=null val = t1
  5. t1 != null, t2=null val = t2
  6. t1 = null, t2 = null val = t2(0)
  7. t1 != null, t2 !=null val = t1+t2
  8. function mergeTrees( t1 , t2 ) {
  9. // write code here
  10. const dfs = (node1, node2) => {
  11. if(node1==null) return node2
  12. if(node2==null) return node1
  13. node1.val += node2.val
  14. node1.left = dfs(node1.left, node2.left)
  15. node1.right = dfs(node1.right, node2.right)
  16. return node1
  17. }
  18. return dfs(t1, t2)
  19. }


二叉树的镜像

输入:{8,6,10,5,7,9,11}

返回值:{8,10,6,11,9,7,5}

image.png

解题思路:左右互换 + 递归
function Mirror( pRoot ) {
    // write code here
    const dfs = (node)=> {
        if(!node) return
        let temp = node.left
        node.left = node.right
        node.right = temp
        dfs(node.left)
        dfs(node.right)
        return node
    }
    return dfs(pRoot)
}