144. Binary Tree Preorder Traver
2017-01-09 本文已影响0人
juexin
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?
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> path;
TreeNode* p = NULL;
if(root == NULL)
return path;
stack<TreeNode*> s;
s.push(root);
while(!s.empty())
{
p = s.top();
path.push_back(p->val);
s.pop();
if(p->right)
s.push(p->right);
if(p->left)
s.push(p->left);
}
return path;
}
};