feat: 94_binary_tree_inorder_traversal
This commit is contained in:
parent
83de8998d7
commit
a66d6116b3
34
94_binary_tree_inorder_traversal/main.cpp
Normal file
34
94_binary_tree_inorder_traversal/main.cpp
Normal file
@ -0,0 +1,34 @@
|
||||
#include <bits/stdc++.h>
|
||||
using namespace std;
|
||||
|
||||
struct TreeNode {
|
||||
int val;
|
||||
TreeNode *left;
|
||||
TreeNode *right;
|
||||
TreeNode() : val(0), left(nullptr), right(nullptr) {}
|
||||
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
|
||||
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
|
||||
};
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
vector<int> inorderTraversal(TreeNode *root) {
|
||||
vector<int> result;
|
||||
unordered_map<TreeNode *, bool> visited;
|
||||
|
||||
function<void(TreeNode *)> dfs = [&](TreeNode *root) {
|
||||
if (root == nullptr) return;
|
||||
if (visited[root]) return;
|
||||
|
||||
visited[root] = true;
|
||||
|
||||
dfs(root->left);
|
||||
result.emplace_back(root->val);
|
||||
dfs(root->right);
|
||||
};
|
||||
|
||||
dfs(root);
|
||||
|
||||
return result;
|
||||
}
|
||||
};
|
Loading…
x
Reference in New Issue
Block a user