LeetCode 145: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 you do it iteratively?

Subscribe to see which companies asked this question

 //利用两个栈s1和s2实现二叉树的后序遍历
 //1.申请一个栈s1,然后将头节点root压入s1中;
 //2.从s1中弹出的节点记为p,然后依次将p的左孩子和右孩子(不为空的话)压入s1中;
 //3.整个过程中,每一个从s1中弹出的节点都放入s2中;
 //4.不断重复步骤2和步骤3,直到s1为空,过程结束。
 //5.最后,从s2中依次弹出节点即可。
 //每棵子树的头节点都是最先从s1中弹出,然后把该节点的孩子节点按照先左再右的顺序压入s1中,那么从s1弹出的顺序就是先右再左
 //所以从s1中弹出的顺序就是根、右、左,然后,s2重新弹出的顺序就变成了左、右、根。
 class Solution {
 public:
	 vector<int> postorderTraversal(TreeNode* root) {
		 stack<TreeNode*> s1;
		 stack<TreeNode*> s2;
		 vector<int> res;
		 if (root == NULL) 
			 return res;
		 TreeNode* p = root;
		 s1.push(root);

		 while (!s1.empty())
		 {
			 p=s1.top();
			 s1.pop();
			 s2.push(p);
			 if (p->left != NULL)
				 s1.push(p->left);
			 if (p->right != NULL)
				 s1.push(p->right);
		 }

		 while (!s2.empty())
		 {
			 p = s2.top();
			 res.push_back(p->val);
			 s2.pop();
		 }

		 return res;
	 }
 };

LeetCode 145:Binary Tree Postorder Traversal_第1张图片

你可能感兴趣的:(LeetCode 145:Binary Tree Postorder Traversal)