Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree
Given binary tree
{1,#,2,3}
,1 \ 2 / 3
return
[1,2,3]
.
Note: Recursive solution is trivial, could you do it iteratively?
Solution :
CODE:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector
vector
stack
if(root!=NULL)
s.push(root);
while(!s.empty()){
TreeNode *curr = s.top();
result.push_back(curr->val);
s.pop();
if(curr->right)
s.push(curr->right);
if(curr->left)
s.push(curr->left);
}
return result;
};