题目: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.将栈顶结点出栈并输出其值;如果该栈顶结点为其父结点的右结点,继续出栈并输出,如果该栈顶结点为其父结点的左结点,判断其父结点的右结点是否为空,如果不为空,将该结点作为根结点重复步骤1,直至栈为空。
vector
postorderTraversal(TreeNode *root)
{
TreeNode *p = root;
stack
record;
vector
res;
if (root == NULL) return res;
do
{
record.push(p);
while (true)
{
if (p->left != NULL)
{
p = p->left;
record.push(p);
}
else if (p->right != NULL)
{
p = p->right;
record.push(p);
}
else
break;
}
while (!record.empty())
{
p = record.top();
res.push_back(p->val);
record.pop();
if (record.empty()) break;
if (record.top()->right != NULL && p != record.top()->right)
{
p = record.top()->right;
break;
}
}
} while (!record.empty());
return res;
}