首页 > 其他 > 详细

Count Complete Tree Nodes

时间:2015-06-09 06:11:31      阅读:235      评论:0      收藏:0      [点我收藏+]

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 Complete Tree Nodes

原文:http://www.cnblogs.com/jiajiaxingxing/p/4562419.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!