-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBST_Successor_Step2.cs
139 lines (122 loc) · 3.57 KB
/
BST_Successor_Step2.cs
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BST_Successor_Step2
{
public class Node
{
public Node left;
public Node right;
public Node parent;
public int val;
public Node(int v)
{
val = v;
}
}
class BST_Successor_Step2
{
static void Main(string[] args)
{
Node n1 = new Node(4);
n1.left = new Node(2);
n1.right = new Node(6);
n1.left.left = new Node(1);
n1.left.right = new Node(3);
n1.right.left = new Node(5);
n1.right.right = new Node(7);
// set parent
n1.parent = null;
n1.left.parent = n1;
n1.left.left.parent = n1.left;
n1.left.right.parent = n1.left;
// set parent
n1.right.parent = n1;
n1.right.left.parent = n1.right;
n1.right.right.parent = n1.right;
Node p3 = getSuccessor(n1.left.right);
Node p4 = getSuccessor(n1);
Console.WriteLine("Node 3's succesor is " + p3.val);
Console.WriteLine("Node 4's successor is " + p4.val);
}
/*
* step 1:
* work on simple test case
*
* 4
* 3 5
*
* There are bugs in the thinking of successor
*
* For node 4, the successor is 5
* For node 5, the successor is null,
* For node 3, the successor is 4
*
* step 2:
*
* Interviewer gives out hint, there are more than 2 cases to fail, and then, Julia gives out the tree based on the advice:
*
* 4
* 2 6
* 1 3 5 7
*
* For node 3, the successor of 3 is 4.
* For node 4, the successor of 4 is 6
*
* And then, julia added her input:
*
* For node 3, the successor of 3 is 4. // To fix the bug, add a function called checkRelationship()
* while retrieving grandParent etc.
* For node 4, the successor of 4 is 6 // To fix the bug, add a function called getLeftMostNode(Node nd)
*
* getLeftMostNode is easy, write the function first.
*/
public static Node getSuccessor(Node nd)
{
if (nd == null)
return null;
if (nd.right == null)
{
Node second;
while (nd.parent != null )
{
second = nd;
nd = nd.parent;
if (checkRelatinship(nd, second))
{
continue;
}
else
return nd;
}
return null;
}
else
return getLeftMostNode(nd.right);
}
private static Node getLeftMostNode(Node nd)
{
if (nd == null) return null;
while (nd.left != null)
{
nd = nd.left;
}
return nd;
}
/*
* 4
* 2 6
* 1 3
*
* 3 -> 2 -> 4
*/
private static bool checkRelatinship(Node nd, Node second)
{
if (nd.right == second)
return true;
return false;
}
}
}