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

222. Count Complete Tree Nodes

时间:2015-11-25 01:56:34      阅读:157      评论: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.

链接: http://leetcode.com/problems/count-complete-tree-nodes/

题解:

求完全二叉树的节点数目。注意完全二叉树和满二叉树Full Binary Tree的唯一区别是,完全二叉树最后一层的节点不满,而且假设最后一层有节点,都是从左边开始。 这样我们可以利用这个性质得到下面两个结论:

  1. 假如左子树高度等于右子树高度,则右子树为完全二叉树,左子树为满二叉树。
  2. 假如高度不等,则左字数为完全二叉树,右子树为满二叉树。
  3. 求高度的时候只往左子树来找。

Time Complexity - O(logn * logn), Space Complexity - O(1) (不考虑递归栈)

/**
 * 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 leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);
        
        if(leftHeight == rightHeight)
            return (1 << leftHeight) + countNodes(root.right);
        else
            return (1 << rightHeight) + countNodes(root.left);
    }
    
    private int getHeight(TreeNode root) {
        int height = 0;
        
        while(root != null) {
            root = root.left;
            height++;
        }
        
        return height;
    }
}

题外话:

高中最好哥们的父亲突然去世了,很为他感到难过,希望他节哀并且早日振作。其实在国外,最担心的就是父母身体,但受签证所限,也许一年也见不到父母一次。父母都已经年近60,算下来以后难道见面时间只有几十次??这样究竟值不值得??这种尴尬窘境,是不是等到绿卡之后才能得以解决。

Reference:

https://leetcode.com/discuss/38884/ac-java-code-any-improvement

https://leetcode.com/discuss/38894/java-solution-clean-code-easy-to-understand

https://leetcode.com/discuss/38899/easy-short-c-recursive-solution

https://leetcode.com/discuss/38919/concise-java-iterative-solution-o-logn-2

https://leetcode.com/discuss/38930/concise-java-solutions-o-log-n-2

https://leetcode.com/discuss/38930/concise-java-solutions-o-log-n-2

https://leetcode.com/discuss/39462/c-solution-inspired-by-couple-of-good-ones

https://leetcode.com/discuss/45260/accepted-clean-java-solution

https://leetcode.com/discuss/57025/68ms-c-solution-using-binary-search-with-brief-explanation

 

222. Count Complete Tree Nodes

标签:

原文地址:http://www.cnblogs.com/yrbbest/p/4993469.html

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