summaryrefslogtreecommitdiff
path: root/week3/Node.cs
blob: 4f1772ad449961067b5c0049c19d2040dd6c797a (plain)
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
using System;
using System.Collections.Generic;

namespace ALGA {
	public class Node {
		public int number { get; private set; }

		public Node left = null;
		public Node right = null;

		public Node(int number) {
			this.number = number;
		}

		public void insert(int value) {
			if (number == value) return;

			if (value > number) {
				if (right != null)
					right.insert(value);
				else
					right = new Node(value);
			} else {
				if (left != null)
					left.insert(value);
				else
					left = new Node(value);
			}
		}

		public Node delete(int value) {
			return delete(this, value);
		}

		private Node delete(Node here, int value) {
			if (here == null) return null;

			if (value > here.number) here.right = delete(here.right, value);
			else if (value < here.number) here.left = delete(here.left, value);
			else {
				if (here.left == null) return here.right;
				if (here.right == null) return here.left;

				here.number = here.left.max().number;
				here.left = delete(here.left, here.number);
			}

			return here;
		}

		public Node min() {
			if (left == null) return this;
			return left.min();
		}

		public Node max() {
			if (right == null) return this;
			return right.max();
		}

		public int count() {
			int sum = 1;
			if (left != null) sum += left.count();
			if (right != null) sum += right.count();
			return sum;
		}

		public int depth() {
			return depth(this);
		}
		private int depth(Node here) {
			if (here == null) return 0;
			return 1 + Math.Max(depth(here.left), depth(here.right));
		}

		public Node find(int value) {
			if (number == value) return this;
			if (value > number && right != null) return right.find(value);
			if (value < number && left != null) return left.find(value);
			return null;
		}

		public List<int> flatten() {
			List<int> flat = new List<int>();

			if (left != null) flat.AddRange(left.flatten());
			flat.Add(number);
			if (right != null) flat.AddRange(right.flatten());

			return flat;
		}

		public List<int> flatten(int min, int max) {
			List<int> flat = new List<int>();

			if (min < number && left != null) flat.AddRange(left.flatten(min, max));
			if (min <= number && number <= max) flat.Add(number);
			if (right != null && number < max) flat.AddRange(right.flatten(min, max));

			return flat;
		}
	}
}