题目:
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() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> res;
void postorder(TreeNode* root)
{
if(root->left)
postorder(root->left);
if(root->right)
postorder(root->right);
res.push_back(root->val);
}
vector<int> postorderTraversal(TreeNode* root) {
res.clear();
if(root == NULL)
return res;
postorder(root);
return res;
}
};
解法二:迭代法
root -> right -> left =====> left -> right -> root
代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> stk;
TreeNode* cur = root;
vector<int> res;
while(cur || !stk.empty())
{
while(cur)
{
res.push_back(cur->val);
stk.push(cur);
cur = cur->right;
}
if(!stk.empty())
{
cur = stk.top()->left;
stk.pop();
}
}
reverse(res.begin(),res.end());
return res;
}
};