Binary Tree postorder Traversal
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 do it iteratively?
Problem Solving Ideas:1. It is very simple to do recursion, walk the left child first, then traverse the right child, then traverse the parent node. The code is as follows:
/** * Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * Tre Enode (int x): Val (x), left (null), right (NULL) {} *}; */class Solution {public: vector<int> postordertraversal (TreeNode *root) { vector<int> result; Postorder (root, result); return result; } void Postorder (TreeNode *node, vector<int>& result) { if (node==null) { return; } Postorder (node->left, result); Postorder (node->right, result); Result.push_back (Node->val); }};
2, but the topic request cannot use recursion. Before the seniors told me thatif recursion is changed to non-recursive, it is simply storing intermediate result with stack or queue. Here we use stacks to store intermediate results. Notice that the backward stack is traversed first, so the most advanced stack is the parent node, then the right child, and finally the left child. Here we need two stacks, one to store the left child stack, and one to store the final result stack. The code is as follows:
/** * Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * Tre Enode (int x): Val (x), left (null), right (NULL) {} *}; */class solution {public:vector<int> Postordertraversal (TreeNode *root) {vector<int> result; Stack<treenode*> s; The final result stack stack<treenode*> sleftnode; Left child stack treenode* node=root; while (node!=null| |! Sleftnode.empty ()) {if (node!=null) {S.push (node); if (node->left!=null) {Sleftnode.push (node->left); } node=node->right; }else{Node=sleftnode.top (); Sleftnode.pop (); }} while (!s.empty ()) {node=s.top (); Result.push_back (Node->val); S.pop (); } return result; }};
[Leetcode] Binary Tree postorder Traversal