LeetCode-Count Complete Tree Nodes

LiBlog發表於2016-08-22

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.

Solution:

 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         return countNodesRecur(root);
14     }
15 
16     public int getLeftHeight(TreeNode cur){
17         int h = 1;
18         while (cur.left!=null){
19             cur = cur.left;
20             h++;
21         }
22         return h;
23     }
24 
25     public int countNodesRecur(TreeNode root){
26         int h = getLeftHeight(root);
27         if (h==1) return 1;
28 
29         if (root.right==null) return 2;
30         int rh = getLeftHeight(root.right);
31 
32         if (rh==h-1){
33             // root.left is a complete tree with height h-1
34             return (1 << rh) -1 + 1 + countNodesRecur(root.right);
35         } else {
36             // root.right is a complete tree with height h-2
37             return (1 << rh) - 1 + 1 + countNodesRecur(root.left);
38         }
39     }
40 }

 

相關文章