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?
Subscribe to see which companies asked this question
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> ans;
stack<TreeNode*> node_list;
if(root == NULL) return ans;
node_list.push(root);
while(!node_list.empty())
{
TreeNode *cur = node_list.top();
node_list.pop();
ans.push_back(cur -> val);
if(cur -> right != NULL) node_list.push(cur -> right);
if(cur -> left != NULL) node_list.push(cur -> left);
}
return ans;
}
};