-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathSuccessor.cs
38 lines (33 loc) · 1.32 KB
/
Successor.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
using System;
namespace PracticeQuestionsSharp.Exercises.Binary_Tree
{
//Write an algorithm to find the "next" node (in-order successor) of a given node in a binary search tree.
// You may assume that each node has a link to it's parent.
public static class Successor
{
public static BinaryTreeNodeWithParent<T> GetSuccessor<T>(this BinaryTreeNodeWithParent<T> node) where T : IComparable<T>
{
if (node.Right != null) return MinNode(node.Right);
while (node.Parent != null)
{
BinaryTreeNodeWithParent<T> prev = node;
node = node.Parent;
if (node?.Left == prev) return node;
}
return null;
}
private static BinaryTreeNodeWithParent<T> MinNode<T>(BinaryTreeNodeWithParent<T> node) where T : IComparable<T>
{
while (node.Left != null) node = node.Left;
return node;
}
}
public class BinaryTreeNodeWithParent<T> where T : IComparable<T>
{
public BinaryTreeNodeWithParent(T data) { Data = data; }
public T Data { get; set; }
public BinaryTreeNodeWithParent<T> Left { get; set; }
public BinaryTreeNodeWithParent<T> Right { get; set; }
public BinaryTreeNodeWithParent<T> Parent { get; set; }
}
}