preorder-traversal-iterative.cpp (1082B)
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 vector<int> preorderTraversal(TreeNode* root) { 15 16 auto nodeLs = vector<TreeNode*>{root}; 17 auto returnLs = vector<int>{}; 18 19 while (nodeLs.size() > size_t(0)) { 20 auto* current = nodeLs.back(); 21 nodeLs.pop_back(); 22 23 if(current == nullptr) { 24 continue; 25 } 26 27 returnLs.push_back(current->val); 28 29 // preorder so we add current then traverse left 30 // then traverse right. (NOTE: Remember this is stack so last item is popped) 31 32 nodeLs.push_back(current->right); 33 nodeLs.push_back(current->left); 34 } 35 36 return returnLs; 37 } 38 };