代码随想录训练营Day17 | 110.平衡二叉树, 257.二

2023-10-30  本文已影响0人  是小张啊啊
110. 平衡二叉树
思路
var isBalanced = function(root) {
    const getDepth = (root) => {
        if (!root) {
            return 0
        }
        let leftDepth = getDepth(root.left)
        if (leftDepth === -1) {
            return -1
        }
        let rightDepth = getDepth(root.right)
        if (rightDepth === -1) {
            return -1
        }
        if (Math.abs(leftDepth - rightDepth) > 1) {
            return -1
        } else {
            return 1 + Math.max(leftDepth, rightDepth)
        }
    }
    return !(getDepth(root) === -1)
};

257. 二叉树的所有路径
思路
var binaryTreePaths = function(root) {
    let res = []
    const getPath = (node, curPath) => {
        if (!node.left && !node.right) {
            curPath += node.val
            res.push(curPath)
            return
        }
        curPath += node.val + "->"
        node.left && getPath(node.left, curPath)
        node.right && getPath(node.right, curPath)
    }
    getPath(root, "");
    return res
};
404. 左叶子之和
思路
var sumOfLeftLeaves = function(root) {
    let res = 0
    const getLeaves = (root) => {
        if (!root) {
            return
        }
        if (root.left && !root.left.left && !root.left.right) {
            res += root.left.val
        }
        getLeaves(root.left)
        getLeaves(root.right)
    }
    getLeaves(root)
    return res
};
上一篇 下一篇

猜你喜欢

热点阅读