[LeetCode]二叉树

  1. 二叉树的中序遍历🟢-- https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
var inorderTraversal = function(root) {//左中右
    const ret=[]
    function inOrder(root){
        if(!root){return ret}
        inOrder(root.left)
        ret.push(root.val)//val
        inOrder(root.right)
    }
    inOrder(root);
    return ret;
};
  1. 相同的树🟢--https://leetcode-cn.com/problems/same-tree/
var isSameTree = function(p, q) {
    if(p===null && q===null){return true}
    if(p===null && q!==null){return false}//2,3行可以合并成if(p===null || q===null)
    if(q===null && p!==null){return false}
    if(p.val!==q.val){return false}
    return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right)
};
  1. 二叉树的层序遍历🟠--https://leetcode-cn.com/problems/binary-tree-level-order-traversal/


  1. 二叉树的最大深度🟢--https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
var maxDepth = function(root) {
    if(!root){return 0}      //终止 递归起始条件
    const left=maxDepth(root.left)
    const right=maxDepth(root.right)
    return Math.max(left,right)+1
};
  1. 翻转二叉树🟢--https://leetcode-cn.com/problems/invert-binary-tree/
var invertTree = function(root) {
    if (root === null) {
        return null;//为啥不能返回[]
    }
    const left = invertTree(root.left);
    const right = invertTree(root.right);
    root.left = right;
    root.right = left;
    return root;
};

如果当前遍历到的节点root 的左右两棵子树都已经翻转,那么我们只需要交换两棵子树的位置,即可完成以root 为根节点的整棵子树的翻转。

posted @ 2022-01-30 20:03  ice猫猫3  阅读(31)  评论(0编辑  收藏  举报