题目:
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?
思路:
刚开始的时候百思不得其解,后来发现其实完全可以参照Leetcode 144的解法。我们只要稍微修改先序遍历(输出根节点后,先遍历右子树,然后遍历左子树),那么得到的结果刚好是后续遍历的逆序。因此思路就很简单了:只需要在Leetcode 144的代码的基础上,加上reverse(ret.begin(), ret.end())即可。时间复杂度和空间复杂度完全同Leetcode 144。
代码:
/**
* 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> ret;
if(root == NULL) {
return ret;
}
stack<TreeNode*> s;
s.push(root);
while(!s.empty()) {
TreeNode* node = s.top();
s.pop();
if(node->left) {
s.push(node->left);
}
if(node->right) {
s.push(node->right);
}
ret.push_back(node->val);
}
reverse(ret.begin(), ret.end());
return ret;
}
};