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?

后序非递归遍历,用栈记录访问路径,并用一个额外的指针来记录前一个访问的节点。
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
   vector<int> postorderTraversal(TreeNode *root) {
	vector<int>vec;
	if (!root)
		return vec;
	stack<TreeNode*>s;
	TreeNode *current=root, *precurrent=NULL;
	do
	{
		while (current)
		{
			s.push(current);
			current = current->left;
		}
		precurrent = NULL;
		while (!s.empty())
		{
			current = s.top();
			if (precurrent == current->right)
			{
				s.pop();
				vec.push_back(current->val);
				precurrent = current;
			}
			else
			{
				current = current->right;
				break;
			}
		}
	} while (!s.empty());
	return vec;
}
};


你可能感兴趣的:(二叉树,非递归,后序遍历)