Problem
Given a binary tree, return the postorder traversal of its nodes' values.For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
Code
vector<int> postorderTraversal(TreeNode *root) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. vector<int> result; if(!root) return result; stack<TreeNode *> st; do{ while(root){ if(root->right) st.push(root->right); st.push(root); root = root->left; } TreeNode *node = st.top(); st.pop(); if(node->right && !st.empty() && node->right == st.top()){ root = st.top(); st.pop(); st.push(node); } else{ result.push_back(node->val); root = 0; } }while(!st.empty()); return result; }
No comments:
Post a Comment