-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* add btree preorder traversal * impl btree preorder traversal
- Loading branch information
Showing
2 changed files
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
#include <stack> | ||
|
||
#include "TestHelper.h" | ||
#include "problem.h" | ||
#include "solution.h" | ||
|
||
using namespace std; | ||
|
||
IMPLEMENT_PROBLEM_CLASS(PBTreePreorderTraversal, 144, DIFFI_MEDIUM, | ||
TOPIC_ALGORITHMS, "Binary Tree Preorder Traversal", | ||
"Given the root of a binary tree, return the preorder " | ||
"traversal of its nodes' values.", | ||
{"Binary Tree"}); | ||
|
||
class SBTreePreorderTraversal : public ISolution { | ||
public: | ||
size_t problemId() const override { return 144; } | ||
string name() const override { | ||
return ("Solution for " + string("Binary Tree Preorder Traversal")); | ||
} | ||
string location() const override { return __FILE_NAME__; } | ||
int test() const override { | ||
return testHelperBinaryTreeV2<vector<int>>( | ||
{"[1,null,2,3]", "[]", "[1]"}, {{1, 2, 3}, {}, {1}}, | ||
[this](auto root) { return this->preorderTraversal(root); }); | ||
}; | ||
int benchmark() const override { return 0; } | ||
|
||
private: | ||
vector<int> preorderTraversal(TreeNode* root) const { | ||
stack<TreeNode*> s = {}; | ||
auto node = root; | ||
vector<int> res; | ||
|
||
while (node || !s.empty()) { | ||
if (node) { | ||
res.push_back(node->val); | ||
s.push(node); | ||
node = node->left; | ||
} else { | ||
auto parent = s.top(); | ||
s.pop(); | ||
node = parent->right; | ||
} | ||
} | ||
|
||
return res; | ||
} | ||
}; |
This file contains 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