leetcode Day18 二叉树

68 阅读1分钟

剑指 Offer 27. 二叉树的镜像

var mirrorTree = function(root) {
    if (root === null) {
        return null;
    }
    const left=mirrorTree(root.left)
    const right=mirrorTree(root.right)
    root.left=right
    root.right=left
    return root
};

剑指 Offer 28. 对称的二叉树

var isSymmetric = function(root) {
    //先镜像再比较
    if(JSON.stringify(root)===JSON.stringify(mirror(root))){
        return true
    }
    return false
};
const mirror=(root)=>{
    if(root===null){
        return null
    }
    let left=mirror(root.left)
    let right=mirror(root.right)
    root.left=right
    root.right=left
    return root
}
var isSymmetric = function(root) {
    //递归比较
    if(root===null)return true
    const compare=(left,right)=>{
        if(!left && !right)return true
        if(!left || !right)return false
        return left.val===right.val && compare(left.left,right.right) && compare(left.right,right.left)
    }
    return compare(root.left,root.right)
};

剑指 Offer 32 - II. 从上到下打印二叉树 II

var levelOrder = function(root) {
    //二叉树层序遍历
    if(!root)return []
    let res=[]
    let queue=[root]
    while(queue.length>0){
        let l=queue.length
        let cur=[]
        for(let i=0;i<l;i++){
            let node=queue.shift()
            cur.push(node.val)
            if(node.left){
                queue.push(node.left)
            }
            if(node.right){
                queue.push(node.right)
            }
        }
        res.push(cur)
    }
    return res
};

剑指 Offer 54. 二叉搜索树的第k大节点

var kthLargest = function(root, k) {
    //逆中序遍历
    if(!root)return 0
    let res=[]
    const dfs=(node)=>{
        if(!node)return
        dfs(node.right)
        res.push(node.val)
        dfs(node.left)
    }
    dfs(root)
    return res[k-1]
};

剑指 Offer 55 - I. 二叉树的深度

var maxDepth = function(root) {
    //深度优先遍历
    if(!root)return 0
    return 1+Math.max(maxDepth(root.left),maxDepth(root.right))
};