Repository navigation
Expand file tree
/
Copy pathFindNodeByPath.cpp
More file actions
82 lines (75 loc) · 1.59 KB
/
Copy pathFindNodeByPath.cpp
File metadata and controls
82 lines (75 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include "pch.h"
#include <iostream>
#include <string>
template <class T>
struct BTNode
{
BTNode(const T& data = new T(), BTNode* left = nullptr, BTNode* right = nullptr) :
data(data),
left(left),
right(right)
{
}
T data;
BTNode<T>* left;
BTNode<T>* right;
};
BTNode<int>* build_sample_tree()
{
BTNode<int>* root = new BTNode<int>(2);
BTNode<int>* n1 = new BTNode<int>(1);
BTNode<int>* n2 = new BTNode<int>(3);
BTNode<int>* n3 = new BTNode<int>(4);
BTNode<int>* n4 = new BTNode<int>(6);
root->left = n1;
root->right = n2;
n2->right = n3;
n3->right = n4;
return root;
}
template <class T>
void In_order_Traversal(const BTNode<T>* root)
{
if (root == nullptr)
{
return;
}
In_order_Traversal(root->left);
std::cout << root->data << " ";
In_order_Traversal(root->right);
}
template <class T>
BTNode<T>* FindNodeByPath(BTNode<T>* root, const std::string& path)
{
if (root == nullptr)
return nullptr;
if (path.empty())
return root;
if (path.size() == 1)
{
if (path == "l")
{
if (root->left)
return root->left;
else return nullptr;
}
if (path == "r")
{
if (root->right)
return root->right;
else nullptr;
}
}
if (*path.begin() == 'l')
return FindNodeByPath(root->left, path.substr(1, path.size() - 1));
else if (*path.begin() == 'r')
return FindNodeByPath(root->right, path.substr(1, path.size() - 1));
}
int main()
{
auto a = build_sample_tree();
In_order_Traversal(a);
std::cout << "\n";
auto node = FindNodeByPath(a, "rrr");
std::cout << "path:rrr " << node->data;
}