代码随想录第十六天|Leetcode104.二叉树的最大深度、Leetcode559.n叉树的最大深度、Leetcode111.二叉树的最小深度、Leetcode222.完全二叉树的节点个数
Leetcode104.二叉树的最大深度
递归写起来还是简单啊
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==NULL) return 0;
return max(maxDepth(root->left),maxDepth(root->right))+1;
}
};
Leetcode559.n叉树的最大深度
递归法确实写起来简单些,层序遍历就是逻辑上更简单些
class Solution {
public:
int maxDepth(Node* root) {
if(root==NULL) return 0;
int result=0;
for(int i=0;i<root->children.size();i++){
result=max(result,maxDepth(root->children[i]));
}
return result+1;
}
};
Leetcode111.二叉树的最小深度
还行,这次能自己写出来了,这个最大的坑在于左右子树都为NULL,才算到叶子节点了。
class Solution {
public:
int minDepth(TreeNode* root) {
if(root==NULL) return 0;
if(root->left==NULL&&root->right==NULL) return 1;
if(root->left==NULL&&root->right!=NULL) return minDepth(root->right)+1;
if(root->left!=NULL&&root->right==NULL) return minDepth(root->left)+1;
return min(minDepth(root->right),minDepth(root->left))+1;
}
};
Leetcode222.完全二叉树的节点个数
层序遍历得心应手啊,好爽
class Solution {
public:
int countNodes(TreeNode* root) {
queue<TreeNode*> que;
int result=0;
if(root!=NULL) que.push(root);
while(!que.empty()){
int size=que.size();
for(int i=0;i<size;i++){
TreeNode* temp=que.front();
que.pop();
result++;
if(temp->left) que.push(temp->left);
if(temp->right) que.push(temp->right);
}
}
return result;
}
};
遍历也不能忘,整一遍,出乎意料的轻松???
class Solution {
public:
int countNodes(TreeNode* root) {
if(root==NULL) return 0;
return countNodes(root->left)+countNodes(root->right)+1;
}
};