本文总结了tree的三种traversal方式, 三种都用到stack。而且只有在inorder的时候while condition有所不同
- Inorder Traversal
https://leetcode.com/problems/binary-tree-inorder-traversal/
while(cur || !st.empty())
, 同时while loop之前不 push stack
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ret;
if(!root){
return ret;
}
stack<TreeNode*> st;
TreeNode *cur = root;
while(cur || !st.empty()){
if(cur){
st.push(cur);
cur = cur->left;
}
else{
TreeNode *node = st.top(); st.pop();
ret.push_back(node->val);
cur = node->right;
}
}
return ret;
}
};
- Preorder Traversal
https://leetcode.com/problems/binary-tree-preorder-traversal/
while(!st.empty())
, , 同时while loop之前 push stack
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
if(!root){
return vector<int>();
}
vector<int> ret;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()){
TreeNode *node = st.top(); st.pop();
ret.push_back(node->val);
if(node->right){
st.push(node->right);
}
if(node->left){
st.push(node->left);
}
}
return ret;
}
};
- Postorder Traversal:
https://leetcode.com/problems/binary-tree-postorder-traversal/
Postorder 与 Preorder模板差不多,只是最后要reverse
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> ret;
if(!root){
return ret;
}
stack<TreeNode*> st;
st.push(root);
while(!st.empty()){
TreeNode* node = st.top(); st.pop();
ret.push_back(node->val);
if(node->left){
st.push(node->left);
}
if(node->right){
st.push(node->right);
}
}
reverse(ret.begin(), ret.end());
return ret;
}
};
网友评论