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

Count Complete Tree Nodes

时间:2015-06-25 12:18:57      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

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 2h nodes inclusive at the last level h.

 

思路

计算根节点的左右子树的高度,如果高度相等则说明是满二叉树,节点数直接使用公式计算:2^h - 1;

否则,对左右孩子递归调用,即countNodes(left) + countNodes(right) + 1.

 

时间/空间复杂度

最好情况下为满二叉树,时间复杂度为O(h);

最坏情况下为O(n) (

 

程序

 

/**
 * 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 lh = getLeftHeight(root);
        int rh = getRightHeight(root);
        
        if (lh == rh) {
            return (1 << lh) - 1;
        }
        return countNodes(root.left) + countNodes(root.right) + 1;
    }
    
    private static int getLeftHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        int count = 0;
        while (root != null) {
            ++count;
            root = root.left;
        }
        
        return count;
    }
    
    private static int getRightHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        int count = 0;
        while (root != null) {
            ++count;
            root = root.right;
        }
        
        return count;
    }
}

 

Count Complete Tree Nodes

标签:

原文地址:http://www.cnblogs.com/harrygogo/p/4599527.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!