algorithms

Algorithm implementations
git clone git://git.laack.co/algorithms.git
Log | Files | Refs | README

preorder-traversal.cpp (891B)


      1 /**
      2  * Definition for a binary tree node.
      3  * struct TreeNode {
      4  *     int val;
      5  *     TreeNode *left;
      6  *     TreeNode *right;
      7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
      8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
      9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
     10  * };
     11  */
     12 class Solution {
     13 public:
     14 
     15     void recurse (TreeNode* current, vector<int>& accumulator) {
     16         if (current == nullptr) {
     17             return;
     18         }
     19 
     20         accumulator.push_back(current->val);
     21 
     22         auto* left = current->left;
     23         auto* right = current->right;
     24 
     25         recurse(left,accumulator);
     26         recurse(right,accumulator);
     27 
     28         return;
     29 
     30     }
     31     vector<int> preorderTraversal(TreeNode* root) {
     32         
     33         auto result =  vector<int>{};
     34         recurse(root, result);
     35         return result;
     36     }
     37 };