leetcode--CountCompleteTreeNodes

complete binary tree:最後一層以上的節點全部排滿,最後一層葉子節點都在左邊。(可能滿也可能不滿)

如果用前序中序或者後序遞歸的話,內存過大,時間也不夠。因此根據complete binary tree的性質,分別求最左子節點和最右子節點的深度,如果相等就根據公式返回,不等再向下遞歸。這樣可以減少遞歸的次數。

/**
 * Created by marsares on 15/6/16.
 */
public class CountCompleteTreeNodes {
    public int countNodes(TreeNode root) {
        if(countLeft(root,0)==countRight(root,0))return twoPower(countLeft(root,0))-1;
        else return countNodes(root.left)+countNodes(root.right)+1;
    }
    private int countLeft(TreeNode root,int height){
        if(root==null)return height;
        return countLeft(root.left,height+1);
    }
    private int countRight(TreeNode root,int height){
        if(root==null)return height;
        return countRight(root.right, height + 1);
    }
    private int twoPower(int n){
        int ans=1;
        for(int i=0;i<n;i++){
            ans=ans*2;
        }
        return ans;
    }
    public static void main(String[]args){
        CountCompleteTreeNodes cctn=new CountCompleteTreeNodes();
        BinaryTreeSerialize bts=new BinaryTreeSerialize();
        TreeNode root=bts.Unserialize("{5,3,8,2,4,7}");
        System.out.println(cctn.countNodes(root));
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章