-
Notifications
You must be signed in to change notification settings - Fork 7
/
Program.cs
111 lines (102 loc) · 2.82 KB
/
Program.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Design;
namespace BinarySearchTreeIterator
{
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int x) { val = x; }
}
class Program
{
static void Main(string[] args)
{
var a = new TreeNode(7);
var b = new TreeNode(3);
var c = new TreeNode(15);
var d = new TreeNode(9);
var e = new TreeNode(20);
a.left = b;
a.right = c;
c.left = d;
c.right = e;
var iterator = new BSTIterator_Queue(a);
Console.WriteLine(iterator.Next());
Console.WriteLine(iterator.Next());
Console.WriteLine(iterator.HasNext());
Console.WriteLine(iterator.Next());
Console.WriteLine(iterator.HasNext());
Console.WriteLine(iterator.Next());
Console.WriteLine(iterator.HasNext());
Console.WriteLine(iterator.Next());
Console.WriteLine(iterator.HasNext());
}
}
public class BSTIterator_LinkedList
{
private ListNode head;
private ListNode point = new ListNode(0);
public BSTIterator(TreeNode root)
{
head = point;
Generate(root);
head = head.next;
}
private void Generate(TreeNode root)
{
if (root == null) return;
Generate(root.left);
point.next = new ListNode(root.val);
point = point.next;
Generate(root.right);
}
/** @return the next smallest number */
public int Next()
{
var res = head.val;
head = head.next;
return res;
}
/** @return whether we have a next smallest number */
public bool HasNext()
{
return head != null;
}
}
public class BSTIterator_Queue
{
private Queue<int> queue;
public BSTIterator(TreeNode root)
{
queue = new Queue<int>();
Generate(root);
}
private void Generate(TreeNode root)
{
if(root == null) return;
Generate(root.left);
queue.Enqueue(root.val);
Generate(root.right);
}
/** @return the next smallest number */
public int Next()
{
return queue.Dequeue();
}
/** @return whether we have a next smallest number */
public bool HasNext()
{
return queue.Count != 0;
}
}
}