Given a binary tree, return the postorder traversal of its nodes' values.
Example:
Input: [1,null,2,3] 1 2 / 3 Output: [3,2,1]
Follow up: Recursive solution is trivial, could you do it iteratively?
方法一:利用两个栈s1,s2来实现,先将头结点入栈s1,从s1弹出栈顶节点记为cur,压入s2中,分别将cur的左右孩子压入s1,当s1为空后,s2的弹出节点次序就是后序遍历的次序。(C++)
1 vector<int> postorderTraversal(TreeNode* root) { 2 stack<TreeNode*> s1,s2; 3 s1.push(root); 4 vector<int> res={}; 5 if(!root) 6 return res; 7 TreeNode* cur; 8 while(!s1.empty()){ 9 cur=s1.top(); 10 s1.pop(); 11 s2.push(cur); 12 if(cur->left) 13 s1.push(cur->left); 14 if(cur->right) 15 s1.push(cur->right); 16 } 17 while(!s2.empty()){ 18 cur=s2.top(); 19 s2.pop(); 20 res.push_back(cur->val); 21 } 22 return res; 23 }
方法二:先将头结点压入栈,怎样判断是该结点是应该输入vector中还是应该处理他的孩子?
1.该节点左右孩子为空时,为叶子结点,则该次遍历是输入到vector中
2.上一次输入的结点为该节点右孩子时,说明该结点的子树处理完毕,这次遍历是输入vector中
3.如果上一次输入的结点为该节点的左孩子,且右孩子为空,则该结点处理完毕,这次遍历就是输入vector中
4.否则说明子树没有被访问,按右、左孩子入栈。(C++)
1 vector<int> postorderTraversal(TreeNode* root) { 2 stack<TreeNode*> s; 3 vector<int> res={}; 4 if(!root) 5 return res; 6 s.push(root); 7 TreeNode* last=NULL; 8 TreeNode* top; 9 while(!s.empty()){ 10 top=s.top(); 11 if((top->left==NULL&&top->right==NULL)||(top->right==NULL&&last==top->left)||(last==top->right&&last!=NULL)){ 12 res.push_back(top->val); 13 last=top; 14 s.pop(); 15 } 16 else{ 17 if(top->right) 18 s.push(top->right); 19 if(top->left) 20 s.push(top->left); 21 } 22 } 23 return res; 24 }
注意此时要加上这个判定条件,若不加,输出的为2,1,没有把3这个结点入栈
方法三:递归方法(C++)
1 void postOrder(TreeNode* root,vector<int> &res){ 2 if(!root) 3 return; 4 postOrder(root->left,res); 5 postOrder(root->right,res); 6 res.push_back(root->val); 7 } 8 9 vector<int> postorderTraversal(TreeNode* root) { 10 vector<int> res={}; 11 if(!root) 12 return res; 13 postOrder(root,res); 14 return res; 15 }