class Solution {
public:
void traversal(TreeNode* cur,vector<int>& vec){
if(cur==NULL) return;
vec.push_back(cur->val);
traversal(cur->left,vec);
traversal(cur->right,vec);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
traversal(root,result);
return result;
}
};
非递归:(中右左)
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> stk;
vector<int> result;
if(root==NULL) return result;
stk.push(root);
while(!stk.empty()){
TreeNode* node = stk.top();
stk.pop();
result.push_back(node->val);
if(node->right!=NULL){
stk.push(node->right);
}
if(node->left!=NULL){
stk.push(node->left);
}
}
return result;
}
};
class Solution {
public:
void traversal(TreeNode* cur,vector<int>& vec){
if(cur==NULL) return;
traversal(cur->left,vec);
traversal(cur->right,vec);
vec.push_back(cur->val);
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
traversal(root,result);
return result;
}
};
非递归:(只是跟前序遍历换了个顺序,中左右)
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> stk;
if(root==NULL) return result;
stk.push(root);
while(!stk.empty()){
TreeNode* node = stk.top();
stk.pop();
result.push_back(node->val);
if(node->left!=NULL){
stk.push(node->left);
}
if(node->right!=NULL){
stk.push(node->right);
}
}
reverse(result.begin(),result.end());
return result;
}
};
class Solution {
public:
void traversal(TreeNode* cur,vector<int>& vec){
if(cur==NULL) return;
traversal(cur->left,vec);
vec.push_back(cur->val);
traversal(cur->right,vec);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
traversal(root,result);
return result;
}
};
非递归:一直走到最左,再弹出元素接着向右;
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> stk;
TreeNode* node = root;
while(node!=NULL||!stk.empty()){
if(node!=NULL){
stk.push(node);
node = node->left;
}else{
node = stk.top();
stk.pop();
result.push_back(node->val);
node = node->right;
}
}
return result;
}
};