递归
LC104
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==nullptr) return 0;
return max(maxDepth(root->left),maxDepth(root->right))+1;
}
};
用的其实就是bfs,遇到叶子节点就结束。
LC111
class Solution {
public:
int minDepth(TreeNode* root) {
if(!root) return 0;
queue<TreeNode*>que;
que.push(root);
int min_depth=0;
while(!que.empty())
{
min_depth++;
int size=que.size();
for(int i=0;i<size;i++)
{
TreeNode*temp=que.front();
que.pop();
if(!temp->left && !temp->right) return min_depth;
if(temp->left) que.push(temp->left);
if(temp->right) que.push(temp->right);
}
}
return min_depth;
}
};
class Solution {
void traversal(TreeNode* cur,vector<int>&vec)
{
if(cur==nullptr) return;
vec.push_back(cur->val);
traversal(cur->left,vec);
traversal(cur->right,vec);
}
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int>vec;
traversal(root,vec);
return vec;
}
};
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int>result;
if(root==nullptr) return result;
st.push(root);
while(!st.empty())
{
TreeNode* node=st.top();
st.pop();
result.push_back(node->val);
if(node->right) st.push(node->right);
if(node->left) st.push(node->left);
}
return result;
}
};
class Solution {
void traversal(TreeNode*cur,vector<int>&vec)
{
if(cur==nullptr) return;
traversal(cur->left,vec);
vec.push_back(cur->val);
traversal(cur->right,vec);
}
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int>vec;
traversal(root,vec);
return vec;
}
};
每棵子树,整棵树左边界入栈,依次弹出的过程中,打印,对弹出节点的右树继续操作。
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int>result;
stack<TreeNode*>st;
TreeNode*cur=root;
while(cur!=nullptr || !st.empty()){
if(cur!=nullptr)
{
st.push(cur);
cur=cur->left;
}
else{
cur=st.top();
st.pop();
result.push_back(cur->val);
cur=cur->right;
}
}
return result;
}
};
class Solution {
void traversal(TreeNode* root,vector<int>&result)
{
if(root==nullptr) return;
traversal(root->left,result);
traversal(root->right,result);
result.push_back(root->val);
}
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int>result;
traversal(root,result);
return result;
}
};
和前序类似,也是栈。只不过最后reverse了一下。
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int>result;
if(root==nullptr) return result;
st.push(root);
while(!st.empty())
{
TreeNode* node=st.top();
st.pop();
result.push_back(node->val);
if(node->left) st.push(node->left);
if(node->right) st.push(node->right);
}
reverse(result.begin(),result.end());
return result;
}
};
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*>que;
if(root!=nullptr) que.push(root);
vector<vector<int>>result;
while(!que.empty()){
int size=que.size();
vector<int>vec;
for(int i=0;i<size;i++)
{
TreeNode* node=que.front();
que.pop();
vec.push_back(node->val);
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
result.push_back(vec);
}
return result;
}
};