码迷,mamicode.com
首页 > 其他好文 > 详细

Count Complete Tree Nodes

时间:2015-06-09 06:12:13      阅读:99      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!