-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path14.PathFromOneNodeToAnother.cpp
124 lines (118 loc) · 2.87 KB
/
14.PathFromOneNodeToAnother.cpp
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
// https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/
/*
Write it again if have time
*/
/**
* Definition for a binary tree node.
* 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
{
private:
TreeNode *lca(TreeNode *root, int node1, int node2)
{
if (root == NULL)
{
return NULL;
}
if (root->val == node1 || root->val == node2)
{
return root;
}
TreeNode *lft = lca(root->left, node1, node2);
TreeNode *rt = lca(root->right, node1, node2);
if (lft == NULL)
{
return rt;
}
if (rt == NULL)
{
return lft;
}
return root;
}
string height(TreeNode *root, int node, string &path)
{
if (root == NULL)
{
return "";
}
if (root->val == node)
{
return path;
}
path += "U";
string pth_lft = height(root->left, node, path);
string pth_rt = height(root->right, node, path);
if (pth_lft.size() > 0)
{
return pth_lft;
}
if (pth_rt.size() > 0)
{
return pth_rt;
}
path.pop_back();
return "";
}
string Marg(TreeNode *st, int end, string &path)
{
if (st == NULL)
{
return "";
}
if (st->val == end)
{
return path;
}
path += "L";
string pth_lft = Marg(st->left, end, path);
path.pop_back();
path += "R";
string pth_rt = Marg(st->right, end, path);
path.pop_back();
if (pth_lft.size() > 0)
{
return pth_lft;
}
if (pth_rt.size() > 0)
{
return pth_rt;
}
return "";
}
public:
string getDirections(TreeNode *root, int startValue, int destValue)
{
TreeNode *LCA = lca(root, startValue, destValue);
string ans1 = "";
string ans2 = "";
string temp = "";
if (LCA->val == startValue)
{
cout << "case 1 " << endl;
ans1 = Marg(LCA, destValue, temp);
}
else if (LCA->val == destValue)
{
cout << "case 2 " << endl;
ans1 = height(LCA, startValue, temp);
}
else
{
cout << "case 3" << endl;
ans1 = height(LCA, startValue, temp);
temp = "";
ans2 = Marg(LCA, destValue, temp);
}
cout << ans1 << " " << ans2 << endl;
return ans1 + ans2;
}
};