代码随想录训练营Day15|102.二叉树层序遍历, 226.翻

2023-10-25  本文已影响0人  是小张啊啊
102. 二叉树的层序遍历
解题思路
var levelOrder = function(root) {
    if (!root) {
        return []
    }
    let size = 1;
    let queue = [root];
    let res = [];
    while (queue.length) {
        let unit = []
        let i = 0;
        size = queue.length;
        while(i < size) {
            let node = queue[0]
            unit.push(node.val)
            queue.shift()
            i++
            node.left && queue.push(node.left)
            node.right && queue.push(node.right)
        }
        res.push(unit)
    }
    return res;
};
226. 翻转二叉树
var invertTree = function(root) {
    if (!root) { return root }
    const overturn = function (root) {
        if (!root) {
            return
        }
        if (root.left || root.right) {
            let temp = root.left
            root.left = root.right
            root.right = temp
        }
        overturn(root.left)
        overturn(root.right)
    }
    overturn(root)
    return root
};
101. 对称二叉树
解题思路
var isSymmetric = function(root) {
    if (!root) return true
    const compare = function(left,right) {
        if (left === null && right === null) {
            return true
        } else if (left === null && right !== null) {
            return false
        } else if (left !== null && right === null) {
            return false
        } else if (left.val !== right.val) {
            return false
        }
        let outSide = compare(left.left, right.right)
        let inSide = compare(left.right, right.left)
        return outSide && inSide
    }
    return compare(root.left, root.right)
};
上一篇下一篇

猜你喜欢

热点阅读