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

Leetcode: Count Complete Tree Nodes

时间:2015-12-19 06:34:20      阅读:142      评论: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.

用暴力法, recursive求会超时 O(N).   如果从某节点一直向左的高度 = 一直向右的高度, 那么以该节点为root的子树一定是perfect binary tree. 而 perfect binary tree的节点数,可以用公式算出 2^h - 1. 如果高度不相等, 则递归调用 return countNode(left) + countNode(right) + 1.  复杂度为O(h^2) 

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public int countNodes(TreeNode root) {
12         if (root == null) return 0;
13         int leftHeight = countLeft(root.left);
14         int rightHeight = countRight(root.right);
15         if (leftHeight == rightHeight) { //perfect binary tree
16             return (1<<(leftHeight+1))-1;
17         }
18         else return countNodes(root.left) + countNodes(root.right) + 1;
19     }
20     
21     public int countLeft(TreeNode root) {
22         int res = 0;
23         while (root != null) {
24             res++;
25             root = root.left;
26         }
27         return res;
28     }
29     
30     public int countRight(TreeNode root) {
31         int res = 0;
32         while (root != null) {
33             res++;
34             root = root.right;
35         }
36         return res;
37     }
38     
39 }

 

Leetcode: Count Complete Tree Nodes

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/5058570.html

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