给定根节点,求完全二叉树的节点数量。

给定根节点root--->递归方法求完全二叉树的节点个数。[时间复杂度要小于O(N) ] O(log(N)^2)

先给出线序遍历的时间复杂度为O(N)的求解方法。


1.设置全局变量记录count;前序遍历二叉树,等于记录下递归的次数。
2.时间复杂度是O(N);
public class Solution {
    private int count=0;
    public int nodeNum(TreeNode root) {
        if(root==null)
            return 0;
        if(root.left!=null){
            count++;
            nodeNum(root.left);
        }
        if(root.right !=null){
            count++;
            nodeNum(root.right);
        }
        return count+1;
    }
}

利用完全二叉树的特性 先判断 再递归
//使用递归求解
//对于节点root,找出root左子树的最左节点的深度 left;
//找出root右子树的最左节点的深度 right;
//if(leftdepth==rightdepth) 那么左子树一定是满二叉树
(这时候吧根节点root的这一个跟满二叉树算在一起 刚好是n=2^h-1+1)
//if(leftdepth>rightdepth) 那么右子树一定是满二叉树,左子树是满二叉树,递归

public class Solution {
    public int nodeNum(TreeNode root) {
       
        if(root==null)
            return 0;
        int cnt=0;
        int ldep=0;TreeNode cur=root.left;
        while(cur != null){
            ldep++;
            cur=cur.left;
        }
        int rdep=0;cur=root.right;
        while(cur!=null){
            rdep++;
            cur=cur.left;
        }
        if(ldep==rdep){
            cnt = (int)Math.pow(2,ldep)+nodeNum(root.right);
            //要加【int】incompatible types: possible lossy conversion from double to int
        }
        if(ldep>rdep){
            cnt = (int)Math.pow(2,rdep)+nodeNum(root.left);
        }
        return cnt;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_33608638/article/details/79944810
今日推荐