Skip to content

Instantly share code, notes, and snippets.

@Kyungpyo-Kim
Last active April 29, 2018 15:30
Show Gist options
  • Save Kyungpyo-Kim/981d30dc813cebaeb1872e13ae8c65bf to your computer and use it in GitHub Desktop.
Save Kyungpyo-Kim/981d30dc813cebaeb1872e13ae8c65bf to your computer and use it in GitHub Desktop.
Algotithm, Binary tree, preorder search (recursive)
/**
* 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> out;
out.push_back(root->val);
if (root->left == NULL){
if (root->right == NULL){
return out;
}else{
vector<int> reout = preorderTraversal(root->right);
out.insert(out.end(), reout.begin(), reout.end());
}
}else{
vector<int> reout = preorderTraversal(root->left);
out.insert(out.end(), reout.begin(), reout.end());
}
return out;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment