222. Count Complete Tree Nodes

题目:

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/

7/19/2017

最近自己没刷出来几道题,没有走心。看别人答案的

 1 public class Solution {
 2     public int countNodes(TreeNode root) {
 3         if (root == null) return 0;
 4         int leftHeight = getHeight(root.left);
 5         int rightHeight = getHeight(root.right);
 6         
 7         if (leftHeight == rightHeight) {
 8             return (1 << leftHeight) + countNodes(root.right);
 9         } else {
10             return (1 << rightHeight) + countNodes(root.left);
11         }
12     }
13     
14     private int getHeight(TreeNode root) {
15         int height = 0;
16         while (root != null) {
17             root = root.left;
18             height++;
19         }
20         return height;
21     }
22 }

别人的答案和解释

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

更多讨论

https://discuss.leetcode.com/category/230/count-complete-tree-nodes

posted @ 2017-07-20 11:06  panini  阅读(225)  评论(0编辑  收藏  举报