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 you do it iteratively?
递归方法
1 /** 2 * Definition for binary tree 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 if(root==NULL) 14 return v; 15 TreeNode *left=root->left,*right=root->right; 16 postorderTraversal(left); 17 postorderTraversal(right); 18 v.push_back(root->val); 19 return v; 20 } 21 22 23 vector<int> v; 24 };
非递归
处理并出栈时判断,该节点是否有子节点或其子节点是否被访问过。并记录上次处理的节点。
1 /** 2 * Definition for binary tree 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> v; 14 if(root==NULL) 15 return v; 16 stack<TreeNode *> tree; 17 tree.push(root); 18 TreeNode *pre=NULL; 19 while(!tree.empty()){ 20 TreeNode *p = tree.top(); 21 if((p->left==NULL&&p->right==NULL)||(pre!=NULL&&(p->left==pre||p->right==pre))){ 22 v.push_back(p->val); 23 pre=p; 24 tree.pop(); 25 }else{ 26 if(p->right!=NULL) 27 tree.push(p->right); 28 if(p->left!=NULL) 29 tree.push(p->left); 30 } 31 } 32 return v; 33 } 34 };