Q144. Binary Tree Preorder Traversal
Last updated
Last updated
/**
* 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> res;
helper(root, res);
return res;
}
private:
void helper(TreeNode* root, vector<int>& res){
if (!root) return;
res.push_back(root->val);
if (root->left) helper(root->left, res);
if (root->right) helper(root->right, res);
}
};/**
* 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> res;
if(!root) return res;
stack<TreeNode*> stk;
stk.push(root);
while(!stk.empty()){
TreeNode* temp = stk.top();
stk.pop();
res.push_back(temp->val);
if (temp -> right) stk.push(temp->right);
if (temp -> left) stk.push(temp->left);
}
return res;
}
};