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]
.
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<int> postorderTraversal(TreeNode* root) { 13 vector<int> res; 14 help(root,res); 15 return res; 16 } 17 void help(TreeNode *root,vector<int> &res) 18 { 19 if(root!=NULL) 20 { 21 help(root->left,res); 22 help(root->right,res); 23 res.push_back(root->val); 24 } 25 } 26 }; 27 class Solution { 28 public: 29 vector<int> postorderTraversal(TreeNode *root) 30 { 31 vector<int> res; 32 stack<pair<TreeNode*,int>> s; 33 s.push(make_pair(root,0)); 34 while(!s.empty()) 35 { 36 TreeNode *now=s.top().first; 37 if(now==NULL) 38 s.pop(); 39 else 40 { 41 switch(s.top().second++) 42 { 43 case 0: 44 s.push(make_pair(now->left,0)); 45 break; 46 case 1: 47 s.push(make_pair(now->right,0)); 48 break; 49 default: 50 s.pop(); 51 52 res.push_back(now->val); 53 break; 54 } 55 } 56 } 57 return res; 58 } 59 };