1.preorder 前序遍历(根左右)
非递归:通过数据结构stack,从root不断取它的的左子树,同时将右子树的值压入vector中
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
vector<int> result;
stack<TreeNode*> s;
s.push(root);
while(!s.empty()){
TreeNode *p=s.top();
s.pop();
while(p!=nullptr){
result.push_back(p->val);
if(p->right!=nullptr)
s.push(p->right);
p=p->left;
}
}
return result;
}
};
递归:
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
vector<int> result;
pre(root,result);
return result;
}
void pre(TreeNode *root,vector<int> &result){
if(root==nullptr)
return;
result.push_back(root->val);
pre(root->left,result);
pre(root->right,result);
}
};
2.inorder 中序遍历(左根右)
非递归:
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
vector<int> result;
stack<TreeNode*> s;
TreeNode *p=root;
while(!s.empty()||p!=nullptr){
while(p!=nullptr){
s.push(p);
p=p->left;
}
if(!s.empty()){
p=s.top();
s.pop();
result.push_back(p->val);
p=p->right;
}
}
return result;
}
};
递归:
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
vector<int> v;
inorder(root,v);
return v;
}
void inorder(TreeNode *root,vector<int> &res){
if(root==nullptr) return;
inorder(root->left,res);
res.push_back(root->val);
inorder(root->right,res);
}
};
3.postorder 后序遍历(右左根)
非递归:
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> res;
if(!root)
return res;
stack<TreeNode *> s;
s.push(root);
while(!s.empty())
{
TreeNode *temp = s.top();
s.pop();
res.push_back(temp->val);
if(temp->left)
s.push(temp->left);
if(temp->right)
s.push(temp->right);
}
reverse(res.begin(),res.end());
return res;
}
};
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> res;
post(root,res);
return res;
}
void post(TreeNode *root,vector<int> &res){
if(root==nullptr)
return;
post(root->left,res);
post(root->right,res);
res.push_back(root->val);
}
};