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]
.
Stack Problem, One example will make this question easy to tackle.
In this example, the post-order sequence is: 4, 5, 2, 6, 3, 1.
The process will be.... We first push 1 onto stack, Get the top element, pop it off, then push the left and right child.....
vector<int> postorderTraversal(TreeNode* root) { if(!root) return {}; vector<int> res; stack<TreeNode*> nodes; nodes.push(root); while(!nodes.empty()) { TreeNode* tmp = nodes.top(); nodes.pop(); res.push_back(tmp->val); if(tmp->left) nodes.push(tmp->left); if(tmp->right) nodes.push(tmp->right); } reverse(res.begin(), res.end()); return res; }