104 二叉树的深度
递归
根节点+左右子树深度的最大值
class Solution {
public:
//递归
int maxDepth(TreeNode* root) {
if(root==nullptr){
return 0;
}
return 1+max(maxDepth(root->left),maxDepth(root->right));
}
};
非递归
就是层序遍历
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
//非递归:层序遍历
int maxDepth(TreeNode* root) {
queue<TreeNode*> que;
if(root!=nullptr){
que.push(root);
}
int depth=0;
while(!que.empty()){
int size=que.size();
depth++;
for(int i=0;i<size;i++){
TreeNode* node=que.front();
que.pop();
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
}
return depth;
}
};
111. 最小深度
和最大深度不一样,这个要考虑只有做、右子树的情况
class Solution {
public:
int minDepth(TreeNode* root) {
//为叶子节点的情况
if(root==nullptr) return 0;
//只有右节点
if(root->left==nullptr&&root->right!=nullptr) return 1+minDepth(root->right);
//只有左节点
if(root->left!=nullptr&&root->right==nullptr) return 1+minDepth(root->left);
return 1+min(minDepth(root->left),minDepth(root->right));
}
};
非递归
同层序遍历,只不过是当找第一个到叶子节点时返回
class Solution {
public:
int minDepth(TreeNode* root) {
queue<TreeNode*> que;
if(root!=nullptr){
que.push(root);
}
int depth=0;
while(!que.empty()){
int size=que.size();
depth++;
for(int i=0;i<size;i++){
TreeNode* node=que.front();
que.pop();
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
//为什么最大深度加一条就对了?
if(node->left==nullptr&&node->right==nullptr) return depth;
}
}
return depth;
}
};
222. 完全二叉树的节点个数
就是遍历
class Solution {
public:
//就是遍历
int countNodes(TreeNode* root) {
stack<TreeNode*> st;
int num=0;
if(root!=nullptr){
st.push(root);
num++;
}
while(!st.empty()){
TreeNode* node=st.top();
st.pop();
if(node->left){
st.push(node->left);
num++;
}
if(node->right){
st.push(node->right);
num++;
}
}
return num;
}
};