https://leetcode.com/problems/count-complete-tree-nodes/
解题思路:
题目要求计算一棵完全二叉树的节点数。首先回顾一下完全二叉树:
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 2^h nodes at the last level h.(via Wikipedia)
完全二叉树是指除了最后一层,其余每层的节点都填满,最后一层的节点尽可能的靠左边, 并且可能有的节点数是 [1 - 2^h] 个。
解这道题分以下几个步骤:
- 计算左子树的高度
- 计算右子树的高度
- 如果左子树的高度等于右子树的高度,那么说明这是一颗满二叉树,总的节点就是 2^h - 1。
- 如果两个高度不相等,那么就递归计算左右子树的节点数。
时间复杂度是 O(h^2),h是树的高度。
注意:if (left == right) return (2 << (left - 1)) - 1;
2^h - 1 的计算。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int countNodes(TreeNode root) {
if (root == null) return 0;
int left = getLeftHeight(root) + 1;
int right = getRightHeight(root) + 1;
if (left == right)
return (2 << (left - 1)) - 1;
else
return countNodes(root.left) + countNodes(root.right) + 1;
}
public int getLeftHeight(TreeNode root) {
if (root == null) return 0;
int height = 0;
while (root.left != null) {
height++;
root = root.left;
}
return height;
}
public int getRightHeight(TreeNode root) {
if (root == null) return 0;
int height = 0;
while (root.right != null) {
height++;
root = root.right;
}
return height;
}
}