代码随想录第15天 | ● 110.平衡二叉树 ● 257. 二叉树的所有路径 ● 404.左叶子之和

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 deepth=function(root){
    if(!root)
        return 0
    let l=0,r=0
     l=deepth(root.left)
     r=deepth(root.right)
     if(Math.abs(r-l)>1) 
        return 10000
    return 1 + Math.max(l,r)
}
var isBalanced = function(root) {
    if(!root) return true 
    if(deepth(root)>10000) return false
    return Math.abs(deepth(root.right)-deepth(root.left))<2
};

递归函数的参数和返回值: 节点 深度值
终止条件:

  • if(!root) return 0//到了叶子节点
  • 如果有深度差大于1,返回10000

单层递归的逻辑: 分别得到左右两边的节点的深度(递归),取左右两边深度值大的+1为自己的深度值,如果左右有深度差大于1结束,如果到了叶子节点返回0

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 path = function(node,curPath,res){
     //2. 确定终止条件,到叶子节点就终止
       if(node.left===null&&node.right===null){
           curPath+=node.val;
           res.push(curPath);
           return ;
       }
       curPath+=node.val+'->'
       node.left&&path(node.left,curPath,res);
       node.right&&path(node.right,curPath,res);

}
var binaryTreePaths = function(root) {
    let res=[]

     path(root,'',res);
   return res;
};

递归函数的参数和返回值: 节点 单条路径的字符串 字符串数组
终止条件: 到叶子节点就终止
单层递归的逻辑: 到叶子节点就终止,把这条路劲字符串导入到res;如果中间节点,字符串为curPath+=node.val+‘->’,然后去遍历左右节点

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 count = 0
        var deep = function (root) {
            if (!root.left && !root.right)
                return 0
            let count = 0
            if (root.left) {
                if (!root.left.left && !root.left.right) count += root.left.val
                else
                    count += deep(root.left)
            }
            if (root.right) count += deep(root.right)
            return count
        }
        var sumOfLeftLeaves = function (root) {

            return deep(root)
        };



递归函数的参数和返回值: 节点 和
终止条件: 叶子节点返回0
单层递归的逻辑: 每个节点都有个count,如果此节点(有左节点)且左节点是叶子节点,count计数,如果左节点是中间节点 count += deep(root.left);如果此节点(有右节点),count += deep(root.right)。
最后返回root的count

你可能感兴趣的:(代码随想录,算法,leetcode,javascript)