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) {
if(root == NULL)
return vector<int>();
stack<TreeNode*> nodeStack;
vector<int> reverseResult;
while(!nodeStack.empty() || root!=NULL)
{
while(root)
{
reverseResult.push_back(root->val);
nodeStack.push(root);
root=root->right;
}
TreeNode* node = nodeStack.top();
nodeStack.pop();
root = node->left;
}
vector<int> result;
for(int i=reverseResult.size()-1; i>=0; i--)
result.push_back(reverseResult[i]);
return result;
}
};