104.二叉树的最大深度
559.N叉树的最小深度
111.二叉树的最小深度
上面三道题昨天完成层序遍历的时候都完成了,今天就不再赘述了。
222.完全二叉树的节点个数
https://leetcode.cn/problems/count-complete-tree-nodes/
一个一个数的方法,时间复杂度为O(n)
class Solution {
public:
int countNodes(TreeNode* root) {
if (!root) return 0;
return countNodes(root->left) + countNodes(root->right) + 1;
}
};
利用完全二叉树的特性的方法,时间复杂度为O(log n × log n)
class Solution {
public:
int countNodes(TreeNode* root) {
if (!root) return 0;
TreeNode* left = root->left;
TreeNode* right = root->right;
int depth = 0;
while(true) {
if(left && right) {
left = left->left;
right = right->right;
depth++;
continue;
}
else if(!left && !right) {
return (2 << depth) - 1;
}
else {
return 1 + countNodes(root->left) + countNodes(root->right);
}
}
}
};