Description
Given a complete binary tree, count the number of nodes.
Note:
Definition of a complete binary tree from Wikipedia:
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 2h nodes inclusive at the last level h.
Example:
Input:
1
/ \
2 3
/ \ /
4 5 6
Output: 6
分析
题目的意思是:给定一个完全二叉树,求其结点的个数。
- 完全二叉树有一个很好的性质,对任一结点,如果其右子树的最大层次为L,则其左子树的最大层次为L或L+l。那么我们可以根据这个规律,分别求出左右子树的高度。如果左右高度一致,则为满二叉树,直接算出结点数就行了;否则分别递归左右子树。
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
if(!root){
return 0;
}
int lh=leftHeight(root);
int rh=rightHeight(root);
if(lh==rh) return pow(2,lh)-1;
return countNodes(root->left)+countNodes(root->right)+1;
}
int leftHeight(TreeNode* root){
if(!root){
return 0;
}
return leftHeight(root->left)+1;
}
int rightHeight(TreeNode* root){
if(!root){
return 0;
}
return rightHeight(root->right)+1;
}
};
Python实现
简单粗暴的遍历
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
l_cnt = self.countNodes(root.left)
r_cnt = self.countNodes(root.right)
return l_cnt+r_cnt+1