Skip to content

Commit 4267a88

Browse files
committed
提交20160725例题与课后作业
0 parents  commit 4267a88

11 files changed

+381
-0
lines changed

binary_tree_inorder_traversal.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
def __init__(self):
5+
self.ret = []
6+
7+
"""
8+
@param root: The root of binary tree.
9+
@return: Preorder in ArrayList which contains node values.
10+
"""
11+
def inorderTraversal(self, root):
12+
# write your code here
13+
if root is not None:
14+
self.inorderTraversal(root.left) # 遍历左子树
15+
self.ret.append(root.val)
16+
self.inorderTraversal(root.right) # 遍历右子树
17+
return self.ret

binary_tree_postorder_traversal.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
def __init__(self):
5+
self.ret = []
6+
7+
"""
8+
@param root: The root of binary tree.
9+
@return: Postorder in ArrayList which contains node values.
10+
"""
11+
def postorderTraversal(self, root):
12+
# write your code here
13+
if root is not None:
14+
self.postorderTraversal(root.left) # 遍历左子树
15+
self.postorderTraversal(root.right) # 遍历右子树
16+
self.values.ret(root.val)
17+
return self.values

binary_tree_preorder_traversal.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
def __init__(self):
5+
self.ret = []
6+
7+
"""
8+
@param root: The root of binary tree.
9+
@return: Preorder in ArrayList which contains node values.
10+
"""
11+
def preorderTraversal(self, root):
12+
# write your code here
13+
if root is not None:
14+
self.ret.append(root.val)
15+
self.preorderTraversal(root.left)
16+
self.preorderTraversal(root.right)
17+
return self.ret

binary_tree_serialization.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
5+
'''
6+
@param root: An object of TreeNode, denote the root of the binary tree.
7+
This method will be invoked first, you should design your own algorithm
8+
to serialize a binary tree which denote by a root node to a string which
9+
can be easily deserialized by your own "deserialize" method later.
10+
'''
11+
def serialize(self, root):
12+
# write your code here
13+
# 分层遍历,子节点为空用#代替,最后清理尾部的所有#。
14+
ret = []
15+
if not root:
16+
return ret
17+
level = [root]
18+
while level:
19+
new_level = []
20+
for node in level:
21+
ret.append(str(node.val) if node else '#')
22+
if node:
23+
new_level.append(node.left)
24+
new_level.append(node.right)
25+
level = new_level
26+
i = len(ret) - 1
27+
while i >= 0:
28+
if ret[i] == '#':
29+
ret.pop()
30+
i -= 1
31+
else:
32+
break
33+
return ret
34+
35+
'''
36+
@param data: A string serialized by your serialize method.
37+
This method will be invoked second, the argument data is what exactly
38+
you serialized at method "serialize", that means the data is not given by
39+
system, it's given by your own serialize method. So the format of data is
40+
designed by yourself, and deserialize it here as you serialize it in
41+
"serialize" method.
42+
'''
43+
def deserialize(self, data):
44+
# write your code here
45+
if not data:
46+
return None
47+
root = TreeNode(data[0])
48+
level = [root]
49+
i = 1
50+
while i < len(data):
51+
new_level = []
52+
for node in level:
53+
node.left = TreeNode(data[i]) if data[i] != '#' else None
54+
if node.left:
55+
new_level.append(node.left)
56+
i += 1
57+
if i < len(data):
58+
node.right = TreeNode(data[i]) if data[i] != '#' else None
59+
if node.right:
60+
new_level.append(node.right)
61+
i += 1
62+
level = new_level
63+
return root
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
"""
5+
@param root: The root of binary tree.
6+
@return: A list of list of integer include
7+
the zig zag level order traversal of its nodes' values
8+
"""
9+
def zigzagLevelOrder(self, root):
10+
# write your code here
11+
ret = []
12+
if not root:
13+
return ret
14+
level = [root] # 当前遍历层
15+
order = 1 # 顺序遍历
16+
while level:
17+
data = []
18+
new_level = [] # 下一次循环遍历层
19+
for node in level:
20+
data.append(node.val)
21+
if order == 1: # 顺序的时候先访问左节点
22+
if node.left:
23+
new_level.append(node.left)
24+
if node.right:
25+
new_level.append(node.right)
26+
else: # 逆序的时候先访问右节点
27+
if node.right:
28+
new_level.append(node.right)
29+
if node.left:
30+
new_level.append(node.left)
31+
order *= -1 # 反转访问顺序
32+
level = new_level
33+
level.reverse() # 殷雯访问顺序反转,该层的数据也要反转。
34+
ret.append(data)
35+
return ret
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
# @param root: a TreeNode, the root of the binary tree
5+
# @return: nothing
6+
def flatten(self, root):
7+
# write your code here
8+
if not root:
9+
return None
10+
head, tail = self.dfs(root)
11+
return head
12+
13+
def dfs(self, root):
14+
if not (root.left or root.right):
15+
return root, root
16+
head, tail = root, root
17+
left_head, left_tail = None, None
18+
right_head, right_tail = None, None
19+
if root.left:
20+
left_head, left_tail = self.dfs(root.left) # 将左子树拆成链表
21+
if root.right:
22+
right_head, right_tail = self.dfs(root.right) # 将右子树拆成链表
23+
if left_head: # 插入左子树拆成的链表
24+
root.right = left_head
25+
left_tail.right = right_head
26+
tail = right_tail if right_tail else left_tail
27+
else: # 没有左子树
28+
tail = right_tail
29+
head.left = None
30+
return head, tail

heapify.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
# @param A: Given an integer array
5+
# @return: void
6+
def heapify(self, A):
7+
# write your code here
8+
'''
9+
为什么从1/2的位置从后往前遍历?
10+
因为对于堆中下标为i的元素,子节点下标为i * 2 + 1和i * 2 + 2,
11+
对于下标大于1/2位置的元素一定是叶子节点,无须做向下调整。
12+
'''
13+
for i in xrange((len(A) - 1) / 2, -1, -1):
14+
while i < len(A):
15+
left, right = i * 2 + 1, i * 2 + 2
16+
min_pos = i
17+
if (left < len(A)) and (A[left] < A[min_pos]):
18+
min_pos = left
19+
if (right < len(A)) and (A[right] < A[min_pos]):
20+
min_pos = right
21+
if min_pos != i: # 调整A[i]元素位置,继续向下调整。
22+
A[i], A[min_pos] = A[min_pos], A[i]
23+
i = min_pos
24+
else: # min_pos没变,A[i]无须调整,结束循环。
25+
break

implement_trie.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class TrieNode:
4+
def __init__(self):
5+
# Initialize your data structure here.
6+
self.map = {} # 记录后序某个字母是否出现
7+
self.isLeaf = False
8+
9+
class Trie:
10+
def __init__(self):
11+
self.root = TrieNode() # 根节点
12+
13+
# @param {string} word
14+
# @return {void}
15+
# Inserts a word into the trie.
16+
def insert(self, word):
17+
root = self.root
18+
for ch in word:
19+
if ch not in root.map:
20+
root.map[ch] = TrieNode() # ch出现并记录
21+
root = root.map[ch]
22+
root.isLeaf = True # 该节点可以为叶子节点
23+
24+
25+
# @param {string} word
26+
# @return {boolean}
27+
# Returns if the word is in the trie.
28+
def search(self, word):
29+
root = self.root
30+
i = 0
31+
for ch in word:
32+
if ch not in root.map: # 找不到匹配字符,直接返回False。
33+
return False
34+
else:
35+
i += 1
36+
if (i == len(word)) and root.map[ch].isLeaf: # 判断是否最后一个字母且为叶子节点
37+
return True
38+
root = root.map[ch]
39+
return False
40+
41+
42+
# @param {string} prefix
43+
# @return {boolean}
44+
# Returns if there is any word in the trie
45+
# that starts with the given prefix.
46+
def startsWith(self, prefix):
47+
root = self.root
48+
for ch in prefix:
49+
if ch not in root.map:
50+
return False
51+
else:
52+
root = root.map[ch]
53+
return True
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
# @param matrix: a matrix of integers
5+
# @param k: an integer
6+
# @return: the kth smallest number in the matrix
7+
def kthSmallest(self, matrix, k):
8+
# write your code here
9+
heap = []
10+
i = 0
11+
while i < len(matrix):
12+
j = 0
13+
while j < len(matrix[0]):
14+
if len(heap) < k: # 先把堆填满
15+
heap.append(matrix[i][j])
16+
self.adjustUp(heap) # 因为新元素添加在尾部,只要做向上调整。
17+
j += 1 # 下一列
18+
else:
19+
if matrix[i][j] < heap[0]:
20+
heap[0] = matrix[i][j] # 因为matrix[i][j]更小,替换原来的根节点。
21+
self.adjustDown(heap) # 因为根节点更新了,所以做向下调整。
22+
j += 1 # 下一列
23+
else:
24+
'''
25+
这段很重要,因为matrix[i][j] > heap[0],
26+
所以对于后面的所有列,不肯能会出现matrix[i][j'] < heap[0],
27+
直接从下一行开始,不然数据量大会超时。
28+
'''
29+
break
30+
i += 1 # 下一行
31+
return heap[0]
32+
33+
def adjustUp(self, heap):
34+
i = len(heap) - 1
35+
while i >= 0:
36+
parent = (i - 1) / 2
37+
if (parent >= 0) and (heap[parent] < heap[i]):
38+
heap[i], heap[parent] = heap[parent], heap[i]
39+
i = parent
40+
else:
41+
break
42+
43+
def adjustDown(self, heap):
44+
i = 0
45+
while i < len(heap):
46+
left, right, max_pos = i * 2 + 1, i * 2 + 2, i
47+
if (left < len(heap)) and (heap[left] > heap[max_pos]):
48+
max_pos = left
49+
if (right < len(heap)) and (heap[right] > heap[max_pos]):
50+
max_pos = right
51+
if max_pos != i:
52+
heap[i], heap[max_pos] = heap[max_pos], heap[i]
53+
i = max_pos
54+
else:
55+
break

lowest_common_ancestor.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
"""
5+
@param root: The root of the binary search tree.
6+
@param A and B: two nodes in a Binary.
7+
@return: Return the least common ancestor(LCA) of the two nodes.
8+
"""
9+
def lowestCommonAncestor(self, root, A, B):
10+
# write your code here
11+
if (not root) or (root == A) or (root == B):
12+
return root
13+
left = self.lowestCommonAncestor(root.left, A, B) # 在左子树找AB的最近公共祖先
14+
right = self.lowestCommonAncestor(root.right, A, B) # 在右子树找AB的最近公共祖先
15+
'''
16+
如果left和right都不会空,说明A、B分别在root的左、右子树,root是最近公共祖先。
17+
如果A、B都在root的左子树,那么right肯定为空,最近公共祖先肯定在左子树中。所以left就是返回最近公共祖先。
18+
'''
19+
if left and right:
20+
return root
21+
else:
22+
return left if left else right

0 commit comments

Comments
 (0)