-
Notifications
You must be signed in to change notification settings - Fork 0
/
count-complete-tree-nodes.js
74 lines (63 loc) · 1.76 KB
/
count-complete-tree-nodes.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var countNodes = function (root) {
// 1. 后序遍历 O(n)
// if (!root) return 0;
// const leftNum = countNodes(root.left); // 左边节点的数量
// const rightNum = countNodes(root.right); // 右边节点的数量
// const treeNum = 1 + leftNum + rightNum; // 以中间节点为根节点的数量 (1 表示中间节点的数量)
// return treeNum;
// 2. 层序遍历 O(n)
// return bfs(root);
// 3. 后序遍历 (完全二叉树) O(log n * log n)
return postOrder(root);
};
function bfs(root) {
if (!root) return 0;
const queue = [root];
let count = 0;
while (queue.length) {
let size = queue.length;
while (size--) {
// 记录节点数
count++;
const node = queue.shift();
node.left && queue.push(node.left);
node.right && queue.push(node.right);
}
}
return count;
}
// O(log n * log n)
function postOrder(root) {
if (!root) return 0;
let left = root.left;
let right = root.right;
let leftHeight = 1, rightHeight = 1;
while (left) { // 计算左子树左侧节点深度
leftHeight++;
left = left.left;
}
while (right) { // 计算右子树右侧节点深度
rightHeight++;
right = right.right;
}
// 判断子树是否是满二叉树
// 满二叉树的节点数目: 2^h-1
if (leftHeight === rightHeight) {
return Math.pow(2, leftHeight) - 1;
}
const leftNum = postOrder(root.left);
const rightNum = postOrder(root.right);
return 1 + leftNum + rightNum;
}