222. Count Complete Tree Nodes

題目:java

Given a complete binary tree, count the number of nodes.node

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.spa

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

7/19/2017blog

最近本身沒刷出來幾道題,沒有走心。看別人答案的ip

 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 }

別人的答案和解釋ci

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

更多討論get

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

相關文章
相關標籤/搜索