Leetcode 刷题Day17 ---------------二叉树

Leetcode 刷题Day17 ---------------二叉树

1. 平衡二叉树 (110)
  • 题目链接:https://leetcode.cn/problems/balanced-binary-tree/
  • 文章讲解/视频讲解:https://programmercarl.com/0110.%E5%B9%B3%E8%A1%A1%E4%BA%8C%E5%8F%89%E6%A0%91.html
class Solution {
    public boolean isBalanced(TreeNode root) {
        return getHeight(root)!=-1;
    }

    public int getHeight(TreeNode root){
        if(root==null) return 0;
        int leftHeight=getHeight(root.left);
        if(leftHeight==-1) return -1;
        int rightHeight=getHeight(root.right);
        if(rightHeight==-1) return -1;
        if(Math.abs(leftHeight-rightHeight)>1) return -1;
        return Math.max(leftHeight,rightHeight)+1;

    }
}
2. 二叉树的所有路径 (257)

根左右:前序遍历

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<Integer> path=new ArrayList<Integer>();//放单条路线的路径
        List<String> res=new ArrayList<String>();//将每条路径保存为结果
        if(root==null) return null;
        traversal(root,path,res);
        return res;
    }

    public void traversal(TreeNode root,List<Integer> path,List<String> res){
        path.add(root.val);
        if(root.left==null&&root.right==null){
            StringBuilder sb=new StringBuilder();
            for(int i=0;i<path.size()-1;i++){
                sb.append(path.get(i)).append("->");
            }
            sb.append(path.get(path.size()-1));
            res.add(sb.toString());
        }
        if(root.left!=null){
            traversal(root.left,path,res);
            path.remove(path.size()-1);//回退
        }
        if(root.right!=null){
            traversal(root.right,path,res);
            path.remove(path.size()-1);//回退
        }
    }

}
3. 左叶子之和 (404)

叶子:左右孩子都为空
左右中 后序遍历:从下往上遍历

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if(root==null) return 0;
        if(root.left==null && root.right==null) return 0;
        int leftSum=sumOfLeftLeaves(root.left);//20行
        if(root.left!=null && root.left.left==null && root.left.right==null) leftSum=root.left.val;//21行
        
        int rightSum=sumOfLeftLeaves(root.right);
        //if(root.right!=null && root.right.left==null && root.right.right==null) leftSum=root.right.val;
        return leftSum+rightSum;
    }
}

20行先计算左子树的左叶子之和
21行是本节点的判断 直接给leftSum赋值的原因是 如果满足了if的那些条件 说明20行计算左子树的结果一定是0 所以直接赋值没问题 当然更好是用+=

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值