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

思路1:

暴力解决,遍历树的所有节点,依次统计。

会超时,题目限定了该二叉树是完全二叉树,该种思路适用于所有二叉树。

思路2:

暴力解决无法测试通过,此时需要考虑完全二叉树的特点。

完全二叉树,至少有一课子树是完美二叉树,另一课子树至少是完全二叉树。

因此可以递归的计算。

判断完美二叉树:

     最内侧的叶子结点和最外侧的叶子结点是否在同一层。

代码:

 1     public static int countNodes(TreeNode root){
 2         if(root == null){
 3             return 0;
 4         }
 5         
 6         int hl = getLeft(root)+1;
 7         int hr = getRight(root)+1;
 8         
 9         if(hl == hr){
10             int num = (2<<(hl-1))-1;
11             return num;
12         }else{
13             return countNodes(root.left)+countNodes(root.right)+1;
14         }
15     }
16 
17     public static int getRight(TreeNode root) {
18         int cou = 0;
19         TreeNode ptr = root;
20         while(ptr.right != null){
21             cou++;
22             ptr = ptr.right;
23         }
24         return cou;
25     }
26 
27     public static int getLeft(TreeNode root) {
28         int cou = 0;
29         TreeNode ptr = root;
30         while(ptr.left != null){
31             cou++;
32             ptr = ptr.left;
33         }
34         return cou;
35     }
原文地址:https://www.cnblogs.com/bywallance/p/5569483.html