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:
[0, 100].-100 <= Node.val <= 100
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> postorderTraversal(TreeNode* root) {
- vector<int> postorder;
- if (root == nullptr) {return postorder;}
- stack
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;
- }
- };
- class Solution {
- public:
- vector<int> postorderTraversal(TreeNode* root) {
- vector<int> res;
- if(!root) return res;
- stack
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;
- }
- };
- /**
- * 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;
- * }
- * }
- */
- class Solution {
- public List
postorderTraversal(TreeNode root) { - List
postorder = new ArrayList<>(); - if (root == null) {return postorder;}
- Stack
st1 = new Stack<>(); - Stack
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;
- }
- }