222. Count Complete Tree Nodes

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

题目含义:给定一个完整二叉树,求所有节点数

百度百科中完全二叉树的定义如下:若设二叉树的深度为h,除第 h 层外,其它各层 (1~h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边,这就是完全二叉树。

方法一:

1 private int height(root)
 { return root == null ? -1 : 1 + height(root.left);

 }
3 public int countNodes(TreeNode root) {
4     int h = height(root);
5     return h < 0 ? 0 :
6            height(root.right) == h-1 ? (1 << h) + countNodes(root.right)
7                                      : (1 << h-1) + countNodes(root.left);
8 }

 

 

方法二:

 1     public int countNodes(TreeNode root) {
 2         //如果是满二叉树,节点总和是(2的深度次方)-1,如果是完全二叉树,节点总和是左右子树的总和加1
 3         if (root == null) return 0;
 4         TreeNode left=root,right=root;
 5         int leftHeight = 0,rightHeight = 0;
 6         while (left!=null)
 7         {
 8             left = left.left;
 9             leftHeight++;
10         }
11         while (right!=null)
12         {
13             right = right.right;
14             rightHeight++;
15         }
16         if (leftHeight == rightHeight) return (int) Math.pow(2,leftHeight)-1;
17         return countNodes(root.left) + countNodes(root.right)+1;        
18     }

 

posted @ 2017-10-25 20:20  daniel456  阅读(134)  评论(0编辑  收藏  举报