-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path144BinaryTreePreorderTraversal.cs
110 lines (84 loc) · 2.55 KB
/
144BinaryTreePreorderTraversal.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _144BinaryTreePreorderTraversal
{
internal class Program
{
private static readonly Queue<Node> Queue = new Queue<Node>();
private static readonly Queue<Node> Queue2 = new Queue<Node>();
private static void Main()
{
var node1 = new Node();
var node2 = new Node();
var node3 = new Node();
var node4 = new Node();
var node5 = new Node();
var node6 = new Node();
var node7 = new Node();
node1.value = 1;
node2.value = 2;
node3.value = 3;
node4.value = 4;
node5.value = 5;
node6.value = 6;
node7.value = 7;
node1.left = node2;
node1.right = node3;
node2.left = node4;
node2.right = node5;
node3.left = node6;
node3.right = node7;
Console.WriteLine("PreorderTraversal");
PreorderTraversal(node1);
Console.WriteLine("PreorderTraversalIterative");
ArrayList list = preorderTraversalIterative(node1);
foreach (Object s in list)
{
int tmp = (int)s;
Console.WriteLine(tmp);
}
Console.ReadLine();
}
private static void PreorderTraversal(Node node)
{
if (node == null)
{
return;
}
Console.WriteLine(node.value.ToString());
PreorderTraversal(node.left);
PreorderTraversal(node.right);
}
private static ArrayList preorderTraversalIterative(Node root)
{
ArrayList result = new ArrayList();
Node p = new Node();
Stack s = new Stack();
p = root;
if (p != null) s.Push(p);
while (s.Count > 0)
{
p = (Node)s.Peek();
s.Pop();
result.Add(p.value);
if (p.right != null) s.Push(p.right);
if (p.left != null) s.Push(p.left);
}
return result;
}
}
internal class Node
{
public int value { get; set; }
public Node left { get; set; }
public Node right { get; set; }
public override string ToString()
{
return value.ToString();
}
}
}