`
hcx2013
  • 浏览: 83373 次
社区版块
存档分类
最新评论

Count Complete Tree Nodes

阅读更多

Given a complete binary tree, count the number of nodes.

Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2hnodes inclusive at the last level h.

 

/**
 * 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;
        }
        return bs(root, 1, mostLeftLevel(root, 1));
    }

	private int bs(TreeNode root, int level, int h) {
		// TODO Auto-generated method stub
		if (level == h) {
			return 1;
		}
		if (mostLeftLevel(root.right, level+1) == h) {
			return (1 << (h - level)) + bs(root.right, level+1, h);
		} else {
			return (1 << (h - level - 1)) + bs(root.left, level+1, h);
		}
	}

	private int mostLeftLevel(TreeNode root, int i) {
		// TODO Auto-generated method stub
		while (root != null) {
			i++;
			root = root.left;
		}
		return i - 1;
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics