树的定义
先序遍历
迭代
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(root==NULL) return res;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()){
TreeNode* top=st.top();
st.pop();
res.push_back(top->val);
if(top->right!=NULL) st.push(top->right);
if(top->left!=NULL) st.push(top->left);
}
return res;
}
};
中序遍历
迭代
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if(root==NULL) return res;
stack<TreeNode*> st;
TreeNode* cur=root;
while(!st.empty()||cur!=NULL){
while(cur!=NULL){
st.push(cur);
cur=cur->left;
}
cur=st.top();
st.pop();
res.push_back(cur->val);
cur=cur->right;
}
return res;
}
};
后序遍历
迭代
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
if(root==NULL) return res;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()){
TreeNode* top=st.top();
st.pop();
res.push_back(top->val);
if(top->left!=NULL) st.push(top->left);
if(top->right!=NULL) st.push(top->right);
}
reverse(res.begin(),res.end());
return res;
}
};