后序遍历
class Solution {
private:
int getNodesNum(TreeNode* cur) {
if (cur == NULL) return 0;
int leftNum = getNodesNum(cur->left); // 左
int rightNum = getNodesNum(cur->right); // 右
int treeNum = leftNum + rightNum + 1; // 中
return treeNum;
}
public:
int countNodes(TreeNode* root) {
return getNodesNum(root);
}
};
完全二叉树的性质
- 当完全二叉树为满二叉树时,结点数量为2^depth-1
- 当完全二叉树不是满二叉树时,分别递归左子树,和右子树,递归到某一深度一定会有左子树或者右子树为满二叉树,然后依然可以按照情况1来计算。、、
class Solution {
public:
int countNodes(TreeNode* root) {
if (root == nullptr) return 0;
TreeNode* left = root->left;
TreeNode* right = root->right;
int leftHeight = 0, rightHeight = 0; // 这里初始为0是有目的的,为了下面求指数方便
while (left) { // 求左子树深度
left = left->left;
leftHeight++;
}
while (right) { // 求右子树深度
right = right->right;
rightHeight++;
}
//满二叉树
if (leftHeight == rightHeight) {
return (2 << leftHeight) - 1; // 注意(2<<1) 相当于2^2,所以leftHeight初始为0
}
//不是满二叉树,当前结点+1然后递归左右子树。
return countNodes(root->left) + countNodes(root->right) + 1;
}
};