您的位置:首页 > Web前端 > Node.js

Count Complete Tree Nodes

2015-06-09 03:32 519 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: