222. Count Complete Tree Nodes (M)
https://leetcode.com/problems/count-complete-tree-nodes/
Input: root = [1,2,3,4,5,6]
Output: 6Input: root = []
Output: 0Input: root = [1]
Output: 1Solution:
一、思路分析
二、复杂度分析
Last updated
https://leetcode.com/problems/count-complete-tree-nodes/
Input: root = [1,2,3,4,5,6]
Output: 6Input: root = []
Output: 0Input: root = [1]
Output: 1Last updated
// 输入一棵完全二叉树,返回节点总数
int countNodes(TreeNode root);public int countNodes(TreeNode root) {
if (root == null) return 0;
return 1 + countNodes(root.left) + countNodes(root.right);
}public int countNodes(TreeNode root) {
int h = 0;
// 计算树的高度
while (root != null) {
root = root.left;
h++;
}
// 节点总数就是 2^h - 1
return (int)Math.pow(2, h) - 1;
}public int countNodes(TreeNode root) {
TreeNode l = root, r = root;
// 记录左、右子树的高度
int hl = 0, hr = 0;
while (l != null) {
l = l.left;
hl++;
}
while (r != null) {
r = r.right;
hr++;
}
// 如果左右子树的高度相同,则是一棵满二叉树
if (hl == hr) {
return (int)Math.pow(2, hl) - 1;
}
// 如果左右高度不同,则按照普通二叉树的逻辑计算
return 1 + countNodes(root.left) + countNodes(root.right);
}return 1 + countNodes(root.left) + countNodes(root.right);