Count Complete Tree Nodes

complete tree, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible.

from wiki

本来在考虑最底层到底满不满,发现是通过recursive 来满足unbalanced的情况

ref http://blog.csdn.net/foreverling/article/details/46387781

/**

 * Definition for a binary tree node.

 * public class TreeNode {

 *     int val;

 *     TreeNode left;

 *     TreeNode right;

 *     TreeNode(int x) { val = x; }

 * }

 */

public class Solution {

    public int countNodes(TreeNode root) {

        if(root==null) return 0;

        int rh = rightH(root);

        int lh = leftH(root);

        if(rh==lh){

            return (int) Math.pow(2,rh)-1;

        }else

            return countNodes(root.left) + countNodes(root.right)+1;

    }

    int rightH(TreeNode root){

        int cnt=1;

        while(root.right!=null){

            cnt++;

            root = root.right;

        }        

        return cnt;

    }

    int leftH(TreeNode root){

        int cnt=1;

        while(root.left!=null){

            cnt++;

            root = root.left;

        }        

        return cnt;

    }

}

 

你可能感兴趣的:(count)