-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path226InvertBinaryTree.cs
124 lines (101 loc) · 3.08 KB
/
226InvertBinaryTree.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/* May 26, 2015 http://arachnode.net/blogs/programming_challenges/archive/2009/09/25/recursive-tree-traversal-orders.aspx
* https://github.com/yuzhangcmu/LeetCode/blob/master/tree/TreeDemo.java
*/
namespace _226InvertBinaryTree
{
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;
// June 16 invert tree
Node resultInvert = invertBinaryTree(node1);
Node resultInvertIter = invertBinaryTreeIterative(node1);
Console.ReadLine();
}
/**
* Latest update: on June 16, 2015
* Leetcode:
* Invert a binary tree
* Reference:
* http://www.zhihu.com/question/31202353
*
* 7 lines of code - using recursion
*/
public static Node invertBinaryTree(Node root)
{
if (root == null)
return null;
Node temp = root.left;
root.left = root.right;
root.right = temp;
invertBinaryTree(root.left);
invertBinaryTree(root.right);
return root;
}
/**
* Latest update: on June 16, 2015
* Leetcode: Invert a binary tree
* using iterative solution
*/
public static Node invertBinaryTreeIterative(Node root)
{
if (root == null)
return null;
Queue q = new Queue();
q.Enqueue(root);
/*
* consider the queue:
*/
while (q.Count > 0)
{
Node nd = (Node)q.Dequeue();
Node tmp = nd.left;
nd.left = nd.right;
nd.right = tmp;
if (nd.left != null)
q.Enqueue(nd.left);
if (nd.right != null)
q.Enqueue(nd.right);
}
return root;
}
}
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();
}
}
}