Leetcode 222.完全二叉树的节点个数

完全二叉树的节点个数

给出一个完全二叉树,求出该树的节点个数。

说明:

完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。

示例:

输入:

1

/ \

2 3

/ \ /

4 5 6

输出: 6

 1 public class Solution {
 2 
 3     // 获取左子树的高度(其实是最左侧分支)
 4     public int getLeftHeight(TreeNode root) {
 5         int count = 0;
 6         while (root != null) {
 7             count++;
 8             root = root.left;
 9         }
10         return count;
11     }
12 
13     // 获取右子树的高度(其实是最右侧分支的高度)
14     public int getRightHeight(TreeNode root) {
15         int count = 0;
16         while (root != null) {
17             count++;
18             root = root.right;
19         }
20         return count;
21     }
22 
23     public int countNodes(TreeNode root) {
24         if (root == null) {
25             return 0;
26         }
27         int leftHeight = getLeftHeight(root);
28         int rightHeight = getRightHeight(root);
29 
30         if (leftHeight == rightHeight) {
31             // 表示是满二叉树,二叉树的节点数直接由公式2^n-1得到
32             // leftHeight即为层数, 1 << leftHeight使用位运算计算2^leftHeight,效率更高
33             // 注意(1 << leftHeight) - 1 的括号必须有!!
34             return (1 << leftHeight) - 1;
35         } else {
36             // 若该二叉树不是满二叉树,递归的调用该方法,计算左子树和右子树的节点数
37             return countNodes(root.left) + countNodes(root.right) + 1;
38         }
39     }
40 }

猜你喜欢

转载自www.cnblogs.com/kexinxin/p/10203064.html