Skip to content

Commit cd3d64d

Browse files
Merge pull request #15 from c344081/master
id 14, 第三次作业
2 parents b84c233 + 5c3febe commit cd3d64d

File tree

11 files changed

+689
-0
lines changed

11 files changed

+689
-0
lines changed

3rd/homework_1/id_14/103.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
"""
2+
Binary Tree Zigzag Level Order Traversal
3+
4+
Given a binary tree, return the zigzag level order traversal of its nodes' values.
5+
(ie, from left to right, then right to left for the next level and alternate between).
6+
7+
For example:
8+
Given binary tree [3,9,20,null,null,15,7],
9+
3
10+
/ \
11+
9 20
12+
/ \
13+
15 7
14+
return its zigzag level order traversal as:
15+
[
16+
[3],
17+
[20,9],
18+
[15,7]
19+
]
20+
"""
21+
22+
# Definition for a binary tree node.
23+
class TreeNode(object):
24+
def __init__(self, x):
25+
self.val = x
26+
self.left = None
27+
self.right = None
28+
29+
from collections import deque
30+
class Solution(object):
31+
def zigzagLevelOrder(self, root):
32+
"""
33+
:type root: TreeNode
34+
:rtype: List[List[int]]
35+
"""
36+
if not root:
37+
return []
38+
queue = deque()
39+
queue.append(root)
40+
results = []
41+
order = 0
42+
while len(queue):
43+
size = len(queue)
44+
currentLevel = []
45+
while size > 0:
46+
node = queue.popleft()
47+
if order:
48+
currentLevel.insert(0, node.val)
49+
else:
50+
currentLevel.append(node.val)
51+
if node.left:
52+
queue.append(node.left)
53+
if node.right:
54+
queue.append(node.right)
55+
size -= 1
56+
if len(currentLevel):
57+
results.append(currentLevel)
58+
order ^= 1
59+
return results
60+
61+
root = TreeNode(3)
62+
root.left = TreeNode(9)
63+
root.right = TreeNode(20)
64+
root.right.left = TreeNode(15)
65+
root.right.right = TreeNode(7)
66+
67+
s = Solution()
68+
list = s.zigzagLevelOrder(root)
69+
for l in list:
70+
for i in l:
71+
print(i)
72+
print("...")

3rd/homework_10/id_14/124.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
"""
2+
Binary Tree Maximum Path Sum
3+
4+
Given a binary tree, find the maximum path sum.
5+
6+
For this problem, a path is defined as any sequence of nodes from some
7+
starting node to any node in the tree along the parent-child connections.
8+
The path must contain at least one node and does not need to go through the root.
9+
10+
For example:
11+
Given the below binary tree,
12+
13+
1
14+
/ \
15+
2 3
16+
Return 6.
17+
"""
18+
# Definition for a binary tree node.
19+
class TreeNode(object):
20+
def __init__(self, x):
21+
self.val = x
22+
self.left = None
23+
self.right = None
24+
25+
import sys
26+
class Solution(object):
27+
def __init__(self):
28+
self.maxValue = -sys.maxsize
29+
def helper(self, root):
30+
if not root:
31+
return 0
32+
left = max(0, self.helper(root.left))
33+
right = max(0, self.helper(root.right))
34+
self.maxValue = max(self.maxValue, left + right + root.val)
35+
return max(left, right) + root.val
36+
def maxPathSum(self, root):
37+
"""
38+
:type root: TreeNode
39+
:rtype: int
40+
"""
41+
if not root:
42+
return 0
43+
self.helper(root)
44+
return self.maxValue

3rd/homework_11/id_14/113.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
"""
2+
Path Sum II
3+
4+
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
5+
6+
For example:
7+
Given the below binary tree and sum = 22,
8+
5
9+
/ \
10+
4 8
11+
/ / \
12+
11 13 4
13+
/ \ / \
14+
7 2 5 1
15+
return
16+
[
17+
[5,4,11,2],
18+
[5,8,4,5]
19+
]
20+
"""
21+
# Definition for a binary tree node.
22+
class TreeNode(object):
23+
def __init__(self, x):
24+
self.val = x
25+
self.left = None
26+
self.right = None
27+
28+
class Solution(object):
29+
def helper(self, results, root, sum, path):
30+
path.append(root.val)
31+
if not root.left and not root.right:
32+
if sum == root.val:
33+
results.append(path[:])
34+
if root.left:
35+
self.helper(results, root.left, sum - root.val, path)
36+
if root.right:
37+
self.helper(results, root.right, sum - root.val, path)
38+
path.pop()
39+
def pathSum(self, root, sum):
40+
"""
41+
:type root: TreeNode
42+
:type sum: int
43+
:rtype: List[List[int]]
44+
"""
45+
if not root:
46+
return []
47+
path = []
48+
results = []
49+
self.helper(results, root, sum, path)
50+
return results
51+

3rd/homework_2/id_14/212.py

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
"""
2+
Word Search II
3+
4+
Given a 2D board and a list of words from the dictionary, find all words in the board.
5+
6+
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent"
7+
cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
8+
9+
For example,
10+
Given words = ["oath","pea","eat","rain"] and board =
11+
12+
[
13+
['o','a','a','n'],
14+
['e','t','a','e'],
15+
['i','h','k','r'],
16+
['i','f','l','v']
17+
]
18+
Return ["eat","oath"].
19+
Note:
20+
You may assume that all inputs are consist of lowercase letters a-z.
21+
"""
22+
23+
# 太慢, 被拒了
24+
class Solution(object):
25+
def isExists(self, board, word, y, x, location):
26+
if len(word) > len(board) * len(board[0]):
27+
return False
28+
if location == len(word):
29+
return True
30+
if y < 0 or x < 0 or y == len(board) or x == len(board[y]):
31+
return False
32+
33+
if board[y][x] != word[location]:
34+
return False
35+
a = ord('#')
36+
board[y][x], a = a, board[y][x]
37+
ret = self.isExists(board, word, y + 1, x, location + 1) \
38+
or self.isExists(board, word, y - 1, x, location + 1) \
39+
or self.isExists(board, word, y, x + 1, location + 1) \
40+
or self.isExists(board,word, y, x - 1, location + 1)
41+
board[y][x], a = a, board[y][x]
42+
return ret
43+
def findWords(self, board, words):
44+
"""
45+
:type board: List[List[str]]
46+
:type words: List[str]
47+
:rtype: List[str]
48+
"""
49+
if not words:
50+
return []
51+
if not board:
52+
return []
53+
results = []
54+
wordDict = {}
55+
for word in words:
56+
if word in wordDict:
57+
continue
58+
59+
wordDict[word] = 0
60+
61+
for y in range(len(board)):
62+
if wordDict[word] > 0:
63+
continue
64+
for x in range(len(board[0])):
65+
if wordDict[word] > 0:
66+
continue
67+
if self.isExists(board, word, y, x, 0):
68+
wordDict[word] += 1
69+
results.append(word)
70+
if len(results) == len(words):
71+
return results
72+
return results
73+
74+
75+
board = [
76+
['a'],
77+
['a']
78+
]
79+
words = ["a"]
80+
81+
s = Solution()
82+
print(s.findWords(board, words))

3rd/homework_3/id_14/112.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
"""
2+
Path Sum
3+
4+
Given a binary tree and a sum, determine if the tree has a root-to-leaf path
5+
such that adding up all the values along the path equals the given sum.
6+
7+
For example:
8+
Given the below binary tree and sum = 22,
9+
5
10+
/ \
11+
4 8
12+
/ / \
13+
11 13 4
14+
/ \ \
15+
7 2 1
16+
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
17+
"""
18+
# Definition for a binary tree node.
19+
class TreeNode(object):
20+
def __init__(self, x):
21+
self.val = x
22+
self.left = None
23+
self.right = None
24+
25+
class Solution(object):
26+
def hasPathSum(self, root, sum):
27+
"""
28+
:type root: TreeNode
29+
:type sum: int
30+
:rtype: bool
31+
"""
32+
if not root:
33+
return False
34+
if root.val == sum and root.left == None and root.right == None:
35+
return True
36+
return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)
37+
38+
sum = 22
39+
root = TreeNode(5)
40+
root.left = TreeNode(4)
41+
root.right = TreeNode(8)
42+
root.left.left = TreeNode(11)
43+
root.left.left.left = TreeNode(7)
44+
root.left.left.right = TreeNode(2)
45+
root.right.left = TreeNode(13)
46+
root.right.right = TreeNode(4)
47+
root.right.right.right = TreeNode(1)
48+
49+
s = Solution()
50+
print(s.hasPathSum(root, sum))
51+
52+

3rd/homework_4/id_14/142.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
"""
2+
Linked List Cycle II
3+
4+
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
5+
6+
Note: Do not modify the linked list.
7+
"""
8+
# Definition for singly-linked list.
9+
class ListNode(object):
10+
def __init__(self, x):
11+
self.val = x
12+
self.next = None
13+
14+
class Solution(object):
15+
def detectCycle(self, head):
16+
"""
17+
:type head: ListNode
18+
:rtype: ListNode
19+
"""
20+
if not head:
21+
return None
22+
runner = head
23+
walker = head
24+
while runner and runner.next:
25+
walker = walker.next
26+
runner = runner.next.next
27+
if walker == runner:
28+
node = head
29+
while node != walker:
30+
walker = walker.next
31+
node = node.next
32+
return node
33+
return None
34+
35+
class Solution2(object):
36+
def detectCycle(self, head):
37+
"""
38+
:type head: ListNode
39+
:rtype: ListNode
40+
"""
41+
if not head:
42+
return None
43+
node = head
44+
nodeSet = set()
45+
while node:
46+
if node in nodeSet:
47+
return node
48+
nodeSet.add(node)
49+
node = node.next
50+
return None
51+
52+
head = ListNode(3)
53+
head.next = ListNode(2)
54+
node = head.next
55+
head.next.next = ListNode(0)
56+
head.next.next.next = ListNode(-4)
57+
head.next.next.next.next = node
58+
59+
s = Solution()
60+
l = s.detectCycle(head)
61+
if l:
62+
print(l.val)
63+
else:
64+
print('Null')

0 commit comments

Comments
 (0)