代码随想录算法训练营第17天 【二叉树④】| 110. 平衡二叉树 257. 二叉树的所有路径 404. 左叶子之和

129 阅读1分钟

110. 平衡二叉树

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isBalanced = function(root) {

    const getDepth = function(node) {
        if (node === null) return 0;
        let leftDepth = getDepth(node.left);
        if (leftDepth === -1) return -1;
        let rightDepth = getDepth(node.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. 二叉树的所有路径

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {string[]}
 */
var binaryTreePaths = function(root) {

    const res = [];

    const getPath = function(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. 左叶子之和

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var sumOfLeftLeaves = function(root) {

    const nodeSum = function(node) {
        // 【注意】
        if (!node) return 0;

        let leftValue = nodeSum(node.left);
        let rightValue = nodeSum(node.right);

        // 左叶子结点只能通过其父去找
        let midValue = 0;
        if (node.left && !node.left.left && !node.left.right) {
            midValue = node.left.val;
        }
        let sum = midValue + leftValue + rightValue;
        return sum;
    }

    return nodeSum(root);
};