您的位置:首页 > 其它

[LeetCode] Binary Tree Preorder Traversal

2015-10-29 04:42 267 查看
The recursive method is trivial. Just record the root and go left and go right.

To do it iteratively, we need a stack to record the path. We go left until it's null. And pop the back out then go the back right. After doing this until stack is empty and root is null. 

vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(root==NULL) return res;
vector<TreeNode*> stack;
while(root!=NULL||!stack.empty())
{
while(root!=NULL)
{
res.push_back(root->val);
stack.push_back(root);
root=root->left;
}
root=stack.back();
stack.pop_back();
root=root->right;
}
return res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode