您的位置:首页 > 其它

[LeetCode] Nonrecursive preorder traversal

2014-12-08 12:39 453 查看
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]
.
下面给出非递归前序遍历的算法,和非递归中序遍历非常像。
vector<int> preorderTraversal(TreeNode *root) {
vector<int> vec; // stores the preorder sequence
stack<TreeNode*> st; // auxiliary stack
TreeNode* curr = root;

while(1)
{
while(curr)
{
vec.push_back(curr->val);
st.push(curr);
curr = curr->left;
}

if(st.size()==0)
break;
else
{
curr = st.top();
curr = curr->right;
st.pop();
}
}

return vec;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: