二叉树前序遍历
递归法
class Solution {
public:
void front(TreeNode* root,vector<int> &res)
{
if(root==nullptr) return;
res.push_back(root->val);
front(root->left,res);
front(root->right,res);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
front(root,res);
return res;
}
};
迭代法
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
if(root==nullptr) return res;
st.push(root);
while(!st.empty())
{
TreeNode* node=st.top();
st.pop();
res.push_back(node->val);
if(node->right) st.push(node->right);
if(node->left) st.push(node->left);
}
return res;
}
};
二叉树的后序遍历
递归法
class Solution {
public:
void back(TreeNode* root,vector<int> &res)
{
if(root==nullptr) return;
back(root->left,res);
back(root->right,res);
res.push_back(root->val);
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
back(root,res);
return res;
}
};
迭代遍历
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
if(root==nullptr) return res;
st.push(root);
while(!st.empty())
{
TreeNode* node=st.top();
st.pop();
res.push_back(node->val);
if(node->left) st.push(node->left);
if(node->right) st.push(node->right);
}
reverse(res.begin(),res.end());
return res;
}
};
二叉树的中序遍历
递归法
class Solution {
public:
void mid(TreeNode* root,vector<int> &res)
{
if(root==nullptr) return;
mid(root->left,res);
res.push_back(root->val);
mid(root->right,res);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
mid(root,res);
return res;
}
};
迭代法
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
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();
res.push_back(cur->val);
cur=cur->right;
}
}
return res;
}
};
二叉树的层序遍历
迭代法
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> que;
if(root!=nullptr) que.push(root);
vector<vector<int>> res;
while(!que.empty())
{
int n=que.size();
vector<int> tmp;
for(int i=0;i<n;i++)
{
TreeNode* node=que.front();
que.pop();
tmp.push_back(node->val);
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
res.push_back(tmp);
}
return res;
}
};
递归法
class Solution {
public:
void ceng(TreeNode* root,vector<vector<int>> &res,int depth)
{
if(root==nullptr) return;
if(res.size()==depth) res.push_back(vector<int>());
res[depth].push_back(root->val);
ceng(root->left,res,depth+1);
ceng(root->right,res,depth+1);
}
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
int depth=0;
ceng(root,res,0);
return res;
}
};