-
Notifications
You must be signed in to change notification settings - Fork 1
/
Contents.swift
152 lines (113 loc) · 2.98 KB
/
Contents.swift
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
//: Playground - noun: a place where people can play
import UIKit
// ListNode Utils
public class ListNode {
public var val: Int
public var next: ListNode?
public init(_ val: Int) {
self.val = val
self.next = nil
}
}
func createListNode(_ list:[Int]) -> ListNode?{
if list.count == 0 {
return nil;
}
let head = ListNode(list.first!)
var node = head;
for i in 1..<list.count {
node.next = ListNode(list[i])
node = node.next!
}
return head;
}
func printListNode(_ listHead:ListNode?) -> String{
var head = listHead!
var resStr = ""
while head.next != nil {
resStr = resStr.appending(" " + String(head.val))
head = head.next!
}
//apend last one
resStr = resStr.appending(" " + String(head.val))
return resStr;
}
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init(_ val: Int) {
self.val = val
self.left = nil
self.right = nil
}
}
//create Tree
func createTreeNode(_ tree:[Int?]) -> TreeNode?{
if tree.count == 0 {
return nil
}
var newTree = tree
//add first
var que:[TreeNode?] = [TreeNode]()
let head = TreeNode(newTree.removeFirst()!)
que.append(head);
while newTree.count > 0 {
let temp = newTree.first!
let headNode = que.first!
var newNode:TreeNode
if temp != nil {
newNode = TreeNode(temp!)
}else{
newNode = TreeNode(Int.max)
}
//sth wrong
assert(headNode != nil, "sth wrong with your array")
if headNode?.left == nil{
headNode?.left = newNode
}else if headNode?.right == nil{
headNode?.right = newNode
}else{
//cannot add
que.removeFirst()
continue
}
//add que
que.append(newNode)
//remove first
newTree.removeFirst()
}
print(head)
return head;
}
//print 🌲
func printTree(_ treeNode:TreeNode) -> String {
var resStr = ""
var queue:[TreeNode?] = [TreeNode]()
queue.append(treeNode)
var res:[String] = [String]()
while !queue.isEmpty {
//remove first leaf
let leaf = queue.removeFirst();
//print leaf
if leaf == nil || leaf?.val == Int.max{
res.append("null")
}else{
res.append(String(leaf!.val))
//leaf in the queue
queue.append(leaf?.left)
queue.append(leaf?.right)
}
}
//remove last null
while res.last == "null" {
res.removeLast()
}
//print
while !res.isEmpty {
resStr += " " + res.removeFirst()
}
return resStr;
}
var test = createTreeNode([3,1,nil,1,nil,3,nil,4])
printTree(test!)