代码随想录day15 Java版 二叉树部分

222.完全二叉树的节点个数

自己做没想出来完全二叉树这个条件怎么利用,直接递归遍历了

class Solution {
    public int countNodes(TreeNode root) {
        if (root == null) return 0;
        return countNodes(root.left)+countNodes(root.right)+1;
    }
}

但看了题解,如果判断子树为满二叉树,可以直接套公式

关键在于怎么判断满二叉树:只需要一直向左和一直向右的深度一样

优化后的代码如下(加入满二叉树的情况)

class Solution {
    public int countNodes(TreeNode root) {
        if (root == null) return 0;
        TreeNode left = root.left;
        TreeNode right = root.right;
        int l = 1, r = 1;
        while(left != null) {
            left = left.left;
            l++;
        }
        while(right != null){
            right = right.right;
            r++;
        }
        if (l == r) return (int)Math.pow(2,l) -1;
        return countNodes(root.left)+countNodes(root.right)+1;
    }
}

110.平衡二叉树

先去看了下二叉树里面的高度和深度

高度是到叶子结点的距离,向上增长,用后序遍历来向上返回递归结果

深度是到根节点的距离    ,向下增长,用前序遍历递归一直向下走

本题的递归套路如下:

1.传入节点,返回高度

2.终止条件:传入的节点为空,此时高度为0,return 0

3.递归部分:采用后序遍历,先左右分别判断子树有没有-1标记,再对当前节点判断是否平衡,如果不平衡就return -1, 平衡就return节点的真实高度

class Solution {
    public boolean isBalanced(TreeNode root) {
        return height(root) != -1;
    }
    public int height(TreeNode root) {
        if (root == null) return 0;
        int l = height(root.left);
        if (l == -1) return -1;
        int r = height(root.right);
        if (r == -1) return -1;
        if (Math.abs(l-r) > 1) return -1;
        return Math.max(l, r) + 1;
    }
}

257. 二叉树的所有路径

从根节点到叶节点,采用前序遍历

结束条件为找到叶子结点

前序遍历中先把当前值加入path,当不是叶子结点时,在左右遍历的时候递归完进行回溯

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        if (root == null) return res;
        List<Integer> path = new ArrayList<>();
        travel(root,path,res);
        return res;
    }
    void travel(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());
            return;
        }
        if (root.left != null){
            travel(root.left, path, res);
            path.remove(path.size()-1);
        }
        if (root.right != null){
            travel(root.right, path, res);
            path.remove(path.size()-1);
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值