题目描述:
Given the root of a complete binary tree, return the number of the nodes in the tree.
According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, 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.
Example 1:
Input: root = [1,2,3,4,5,6]
Output: 6
Example 2:
Input: root = []
Output: 0
Example 3:
Input: root = [1]
Output: 1
Constraints:
The number of nodes in the tree is in the range [0, 5 * 104].
0 <= Node.val <= 5 * 104
The tree is guaranteed to be complete.
Follow up:
Traversing the tree to count the number of nodes in the tree is an easy solution but with O(n) complexity. Could you find a faster algorithm?
Time complexity: O(n)
DFS:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int countNodes(TreeNode root) {
if(root == null){
return 0;
}else{
return 1+countNodes(root.left) + countNodes(root.right);
}
}
}
Time complexity: O((logn)2)
完全二叉树性质+特殊的二分:
每次判断左右深度的时间复杂度是O(logn)),需要判断O(logn)次。
每次判断左右树时必有一个树为完全二叉树性质,则此树的节点个数为2*d-1. d为此树的高度。
class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
int lh = left(root);
int rh = right(root);
if(lh == rh){
return (1<<lh) - 1;
}else{
return 1 + countNodes(root.left) + countNodes(root.right);
}
}
int left(TreeNode root){
int d = 0;
while(root != null){
root = root.left;
d++;
}
return d;
}
int right(TreeNode root){
int d = 0;
while(root != null){
root = root.right;
d++;
}
return d;
}
}