算法随想录算法训练营第十五天| 平衡二叉树 二叉树的所有路径 左叶子之和

目录

              平衡二叉树  

              二叉树的所有路径

              左叶子之和 


平衡二叉树  

文章讲解:代码随想录

class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null)
            return true;
        int left = Depth(root.left);
        int right = Depth(root.right);
        if(Math.abs(left-right)>1)
            return false;
        boolean l = isBalanced(root.left);
        boolean r = isBalanced(root.right);
        return l && r; 
    }

    //找出树的最大深度
    public int Depth(TreeNode node){
        if(node == null){
            return 0;
        }
        int left = Depth(node.left);
        int right = Depth(node.right);
        return Math.max(left,right)+1;
    }
}

二叉树的所有路径

文章讲解:代码随想录

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
       List<String> list = new ArrayList<>();
       if(root == null)
            return list;
        function(root,list,"");
        return list;
    }

    public void function(TreeNode root,List<String> list,String path){
        if(root != null){
            StringBuilder str = new StringBuilder();
            str.append(path);
            str.append(String.valueOf(root.val));
            if(root.left == null && root.right == null){
                list.add(str.toString());
            }else{
                str.append("->");
                function(root.left,list,str.toString());
                function(root.right,list,str.toString());
            }
        }
    }
}

 左叶子之和 

文章讲解:代码随想录


class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if(root == null)
            return 0;
        int leftValue = sumOfLeftLeaves(root.left);
        int rightValue = sumOfLeftLeaves(root.right);
        int value = 0;
        if(root.left!=null && root.left.left==null&&root.left.right==null){
            value = root.left.val;
        }
        int sum = value+leftValue+rightValue;
        return sum;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值