Last active
June 14, 2021 05:37
-
-
Save sourabh2k15/eddb71ac29fb36a0d9da79d037761c32 to your computer and use it in GitHub Desktop.
Leetcode 144. Binary Tree Preorder Traversal. Using stack to perform DFS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Solution { | |
| public: | |
| // DFS magic : initialize stack and do the following | |
| // pop top, retrieve neighbours for top, push unvisited neighbours to stack | repeat while stack not empty | |
| // because this is a tree no need to keep track of visited as no cycles possible. | |
| vector<int> preorderTraversal(TreeNode* root) { | |
| stack<TreeNode*> s; | |
| vector<int> result; | |
| s.push(root); | |
| while(!s.empty()){ | |
| TreeNode* current = s.top(); s.pop(); // pop top | |
| if(current != NULL){ | |
| // push unvisited neighbours to stack | order matters here, if you reverse it | |
| // it would still be a DFS but a symmetric one to preorder out of the 6 possible combinations. | |
| s.push(current->right); | |
| s.push(current->left); | |
| result.push_back(current->val); | |
| } | |
| } | |
| return result; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment