Fork me on GitHub

145. Binary Tree Postorder Traversal

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?

非递归实现二叉树的后序遍历

/**
 * Definition for a binary tree node.
 * 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) {
		stack<TreeNode*> sta;

		TreeNode* cur;
		TreeNode* pre=NULL;
		vector<int> vec;
		if (root==NULL)
		{
			return vec;
		}
		if (root->left == NULL&&root->right == NULL)
		{
			vec.push_back(root->val);
			return vec;
		}
		else
		{
			sta.push(root); //保证左节点先于右节点被访问,根节点后于左右节点被访问
			while (!sta.empty())
			{
			    cur = sta.top();			

				if ((cur->left==NULL&&cur->right==NULL)||pre!=NULL&&(pre==cur->left||pre==cur->right))
				{ //访问该节点
					vec.push_back(cur->val);
					sta.pop();
					pre = cur;
				}
				else
				{
					if (cur->right)
					{
						sta.push(cur->right);
					}
					if (cur->left)
					{
						sta.push(cur->left);
					}
				}
			}
		}
		return vec;
	}
};

145. Binary Tree Postorder Traversal

posted @ 2017-12-21 15:12  ranjiewen  阅读(184)  评论(0编辑  收藏  举报