day16
普通的写法:
后序遍历二叉树(没有利用到二叉树的特性
class Solution {
public:
int countNodes(TreeNode* root) {
if(root == nullptr)
return 0;
int leftnum = countNodes(root->left);
int rightnum = countNodes(root->right);
int sum = leftnum + rightnum + 1;
return sum;
}
};
满完全二叉树特点:
从根节点一直向左或者一直向右去遍历,得到的深度是一样的。
如果深度不一样,就向下一层去遍历,最终最坏的情况就是到最后一个结点,一定是满完全二叉树,就向上返回。
降低了时间复杂度,此时不用去遍历所有的结点。
注意:
1.有两个终止条件,一个是root == nullptr 另一个是一直向左遍历 与 一直向右遍历的深部一样
2. 2 << leftdepth 相当于是 2 的 leftdepth + 1 次方。所以一开始深度的定义是从 0 开始的,原因就是因为这里对 leftdpth + 1 了。就相当于是从 1 开始计算深度。
代码如下:
class Solution {
public:
int countNodes(TreeNode* root) {
// 终止条件:
if(root == nullptr)
return 0;
TreeNode* left = root->left;
TreeNode* right = root->right;
int leftdepth = 0, rightdepth = 0;
while(left)
{
left = left->left;
leftdepth++;
}
while(right)
{
right = right->right;
rightdepth++;
}
if(leftdepth == rightdepth) return (2 << leftdepth) - 1;
// 单层递归逻辑
int leftnum = countNodes(root->left);
int rightnum = countNodes(root->right);
int sum = leftnum + rightnum + 1; // 左子树 + 右子树 + 当前根节点
return sum;
}
};