給定根節點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;
}
}