Leetcode: 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.

递归树高法

复杂度

时间 O(N) 空间 O(1)

思路

完全二叉树的一个性质是,如果左子树最左边的深度,等于右子树最右边的深度,说明这个二叉树是满的,即最后一层也是满的,则以该节点为根的树其节点一共有2^h-1个。如果不等于,则是左子树的节点数,加上右子树的节点数,加上自身这一个。

注意

  • 这里在左节点递归时代入了上次计算的左子树最左深度减1,右节点递归的时候代入了上次计算的右子树最右深度减1,可以避免重复计算这些深度

  • 做2的幂时不要用Math.pow,这样会超时。用1<<height这个方法来得到2的幂

 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         int leftHeight = countLeft(root);
14         int rightHeight = countRight(root);
15         if (leftHeight == rightHeight) { //perfect binary tree
16             return (1<<leftHeight)-1;
17         }
18         else return countNodes(root.left) + countNodes(root.right) + 1;
19     }
20     
21     public int countLeft(TreeNode root) {
22         int res = 0;
23         while (root != null) {
24             res++;
25             root = root.left;
26         }
27         return res;
28     }
29     
30     public int countRight(TreeNode root) {
31         int res = 0;
32         while (root != null) {
33             res++;
34             root = root.right;
35         }
36         return res;
37     }
38     
39 }

迭代树高法

参考https://segmentfault.com/a/1190000003818177

复杂度

时间 O(N) 空间 O(1)

思路

用迭代法的思路稍微有点不同,因为不再是递归中那样的分治法,我们迭代只有一条正确的前进方向。所以,我们判断的时左节点的最左边的深度,和右节点的最左边深度。因为最后一层结束的地方肯定在靠左的那侧,所以我们要找的就是这个结束点。如果两个深度相同,说明左子树和右子树都是满,结束点在右侧,如果右子树算出的最左深度要小一点,说明结束点在左边,右边已经是残缺的了。根据这个大小关系,我们可以确定每一层的走向,最后找到结束点。另外,还要累加每一层的节点数,最后如果找到结束点,如果结束点是左节点,就多加1个,如果结束点是右节点,就多加2个。

注意

  • 同样的,记录上次计算的最左深度,可以减少一些重复计算

  • 用int记录上次最左深度更快,用Integer则会超时

原文地址:https://www.cnblogs.com/EdwardLiu/p/5058570.html