代码随想录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(

你可能感兴趣的:(代码随想录打卡,算法,leetcode,数据结构)