代码随想录| Day 13| 二叉树 part 02 | 102. 二叉树的层序遍历 | 226.翻转二叉树 | 101. 对称二叉树

103 阅读1分钟

102. 二叉树的层序遍历

var levelOrder = function(root) {   
    let stack = []
    stack.push(root)
    let cur = null
    let res = []
    while(stack.length && root !==null){
        let length = stack.length
        let curRes = []
        while(length-- ){
            cur = stack.shift()
            curRes.push(cur.val)
            if(cur.left) stack.push(cur.left)
            if(cur.right) stack.push(cur.right)
       
        }
       res.push(curRes)
        
    }
    return res
};

226.翻转二叉树

var invertTree = function(root) {

    function resversal(node){
        if(node==null)return 

        [node.left,node.right] = [node.right,node.left]
        resversal(node.left)
        resversal(node.right)
    }
    
    resversal(root)
    return root
};

101. 对称二叉树

var isSymmetric = function(root) {
    function check(p,q){
        if(!p && !q)return true
        if(!p || !q)return false

        return p.val === q.val && check(p.left, q.right) && check(p.right, q.left);
    }
    return check(root,root)
};