题目:
Given a binary tree, return the postorder traversal of its nodes' values.
Example:
Input:[1,null,2,3]
1 \ 2 / 3 Output:[3,2,1]
Follow up: Recursive solution is trivial, could you do it iteratively?
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
if (!root)return res;
stack<TreeNode*> s;
map<TreeNode*, int>m;
s.push(root);
while (!s.empty()) {
TreeNode* t = s.top();
bool flag = false;
if (t->right) {
if (m[t->right]!=1) {
s.push(t->right);
flag = true;
}
}
if (t->left) {
if (m[t->left]!=1) {
s.push(t->left);
flag = true;
}
}
if (!t->right && !t->left||!flag) {
s.pop();
res.push_back(t->val);
m[t] = 1;
}
}
return res;
}
};