题目:
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [1,2,3]
.
Note: Recursive solution is trivial, could you do it iteratively?
算法思想:参见点击打开链接
vector
preorderTraversal(TreeNode *root)
{
TreeNode *p = root;
stack
record;
vector
res;
if (root == NULL) return res;
do
{
record.push(p);
res.push_back(p->val);
while (true)
{
if (p->left != NULL)
{
p = p->left;
record.push(p);
res.push_back(p->val);
}
else if (p->right != NULL)
{
p = p->right;
record.push(p);
res.push_back(p->val);
}
else
break;
}
while (!record.empty())
{
p = record.top();
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;
}