题目描述
题目链接
https://leetcode.com/problems/count-complete-tree-nodes/
方法思路
Approach1:recursive dfs 很常规的方法
class Solution {
//Runtime: 0 ms, faster than 100.00%
//Memory Usage: 41.1 MB, less than 5.27%
public int countNodes(TreeNode root) {
if(root == null) return 0;
int left = countNodes(root.left);
int right = countNodes(root.right);
return left + right + 1;
}
}
Approach2: 神级方法
class Solution {
//Runtime: 0 ms, faster than 100.00%
//Memory Usage: 39.3 MB, less than 91.14%
int height(TreeNode root) {
return root == null ? -1 : 1 + height(root.left);
}
public int countNodes(TreeNode root) {
int h = height(root);
return h < 0 ? 0 :
height(root.right) == h-1 ? (1 << h) + countNodes(root.right)
: (1 << h-1) + countNodes(root.left);
}
}
Approach3:
方法2的迭代版本
class Solution {
//Runtime: 0 ms, faster than 100.00%
//Memory Usage: 40.9 MB, less than 5.27%
int height(TreeNode root) {
return root == null ? -1 : 1 + height(root.left);
}
public int countNodes(TreeNode root) {
int nodes = 0, h = height(root);
while (root != null) {
if (height(root.right) == h - 1) {
nodes += 1 << h;
root = root.right;
} else {
nodes += 1 << h-1;
root = root.left;
}
h--;
}
return nodes;
}
}