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

leetcode110.平衡二叉树

注意:×

  1. -1 表示已经不是平衡二叉树了,否则返回值是以该节点为根节点树的高度int getHeight(TreeNode* node)
  2. 注意对leftDep和rightDep进行提前判断
  3. !!!!!!!!!!!!!!!!!getDep函数返回的时候注意Math.max(leftDep,rightDep)+1
    public boolean isBalanced(TreeNode root) {
        if (root == null){
            return true;
        }else {
            return Math.abs(getDep(root.left) - getDep(root.right)) <= 1;
        }
    }

    int getDep(TreeNode node){
        if (node == null){
            return 0;
        }

        int leftDep = getDep(node.left);
        if (leftDep==-1){
            return -1;
        }
        int rightDep = getDep(node.right);
        if (rightDep==-1){
            return -1;
        }
        return Math.abs(leftDep-rightDep)>1 ? -1:Math.max(leftDep,rightDep)+1;
    }

leetcode257. 二叉树的所有路径

注意:×

  1. 注意List<String> paths = new ArrayList<String>();List是继承ArrayList的
  2. 全新的traverse函数的传递方式,传递了TreeNode root, String path, List<String> paths
  3. 一定要反复看的题目
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> paths = new ArrayList<String>();
        constructPaths(root, "", paths);
        return paths;
    }

    public void constructPaths(TreeNode root, String path, List<String> paths) {
        if (root != null) {
            StringBuffer pathSB = new StringBuffer(path);
            pathSB.append(Integer.toString(root.val));
            if (root.left == null && root.right == null) {  // 当前节点是叶子节点
                paths.add(pathSB.toString());  // 把路径加入到答案中
            } else {
                pathSB.append("->");  // 当前节点不是叶子节点,继续递归遍历
                constructPaths(root.left, pathSB.toString(), paths);
                constructPaths(root.right, pathSB.toString(), paths);
            }
        }
    }

leetcode404.左叶子之和

注意:×

  1. 满巧妙的题目,额外使用res来进行补充
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int res1 = 0;
        if (root.left != null && root.left.left == null && root.left.right == null) {
            res1 = root.left.val;
        }
        return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right)+res1;

    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值