Skip to content

Commit

Permalink
Btree preorder traversal (#181)
Browse files Browse the repository at this point in the history
* add btree preorder traversal

* impl btree preorder traversal
  • Loading branch information
SKTT1Ryze authored Mar 5, 2024
1 parent a43be7a commit 00c28dd
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
49 changes: 49 additions & 0 deletions leetcode-cc/BTreePreorderTraversal.hpp
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;
}
};
8 changes: 8 additions & 0 deletions runtime-cc/src/registration.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

#include "../leetcode-cc/BTreeLevelTraversalII.hpp"
#include "../leetcode-cc/BTreeMaxPathSum.hpp"
#include "../leetcode-cc/BTreePreorderTraversal.hpp"
#include "../leetcode-cc/BTreeZigzagLevelOrderTraversal.hpp"
#include "../leetcode-cc/BalancedBTree.hpp"
#include "../leetcode-cc/BestTimeToBuySellStockIII.hpp"
Expand Down Expand Up @@ -605,5 +606,12 @@ const int registerAll(std::shared_ptr<Container> handle) {
handle->registerSolution(
[]() -> ArcSolution { return std::make_shared<SReorderList>(); });

handle->registerProblem([]() -> ArcProblem {
return std::make_shared<PBTreePreorderTraversal>();
});
handle->registerSolution([]() -> ArcSolution {
return std::make_shared<SBTreePreorderTraversal>();
});

return 0;
}

0 comments on commit 00c28dd

Please sign in to comment.