Given the root
of a binary tree, return the postorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3] Output: [3,2,1]
Example 2:
Input: root = [] Output: []
Example 3:
Input: root = [1] Output: [1]
Constraints:
- The number of the nodes in the tree is in the range
[0, 100]
. -100 <= Node.val <= 100
Follow up: Recursive solution is trivial, could you do it iteratively?
【C++】
/**
* 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) {}
* };
*/
1. 双栈
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> postorder;
if (root == nullptr) {return postorder;}
stack<TreeNode*> st1, st2;
st1.push(root);
while (!st1.empty()){
root = st1.top();
st1.pop();
st2.push(root);
if (root->left != nullptr) {st1.push(root->left);}
if (root->right != nullptr) {st1.push(root->right);}
}
while (!st2.empty()){
postorder.push_back(st2.top()->val);
st2.pop();
}
return postorder;
}
};
2. 单栈反序
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()) {
TreeNode* temp = st.top(); st.pop();
if(temp->left) st.push(temp->left);
if(temp->right) st.push(temp->right);
res.push_back(temp->val);
}
reverse(res.begin(),res.end());
return res;
}
};
【Java】
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
1. 双栈
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> postorder = new ArrayList<>();
if (root == null) {return postorder;}
Stack<TreeNode> st1 = new Stack<>();
Stack<TreeNode> st2 = new Stack<>();
st1.push(root);
while (!st1.isEmpty()){
root = st1.pop();
st2.push(root);
if (root.left != null) {st1.push(root.left);}
if (root.right != null) {st1.push(root.right);}
}
while (!st2.isEmpty()){
postorder.add(st2.pop().val);
}
return postorder;
}
}