Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions 3rd/homework_1/id_14/103.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
"""
Binary Tree Zigzag Level Order Traversal

Given a binary tree, return the zigzag level order traversal of its nodes' values.
(ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
"""

# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None

from collections import deque
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
queue = deque()
queue.append(root)
results = []
order = 0
while len(queue):
size = len(queue)
currentLevel = []
while size > 0:
node = queue.popleft()
if order:
currentLevel.insert(0, node.val)
else:
currentLevel.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
size -= 1
if len(currentLevel):
results.append(currentLevel)
order ^= 1
return results

root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right.left = TreeNode(15)
root.right.right = TreeNode(7)

s = Solution()
list = s.zigzagLevelOrder(root)
for l in list:
for i in l:
print(i)
print("...")
44 changes: 44 additions & 0 deletions 3rd/homework_10/id_14/124.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
"""
Binary Tree Maximum Path Sum

Given a binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some
starting node to any node in the tree along the parent-child connections.
The path must contain at least one node and does not need to go through the root.

For example:
Given the below binary tree,

1
/ \
2 3
Return 6.
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None

import sys
class Solution(object):
def __init__(self):
self.maxValue = -sys.maxsize
def helper(self, root):
if not root:
return 0
left = max(0, self.helper(root.left))
right = max(0, self.helper(root.right))
self.maxValue = max(self.maxValue, left + right + root.val)
return max(left, right) + root.val
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
self.helper(root)
return self.maxValue
51 changes: 51 additions & 0 deletions 3rd/homework_11/id_14/113.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""
Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None

class Solution(object):
def helper(self, results, root, sum, path):
path.append(root.val)
if not root.left and not root.right:
if sum == root.val:
results.append(path[:])
if root.left:
self.helper(results, root.left, sum - root.val, path)
if root.right:
self.helper(results, root.right, sum - root.val, path)
path.pop()
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
if not root:
return []
path = []
results = []
self.helper(results, root, sum, path)
return results

82 changes: 82 additions & 0 deletions 3rd/homework_2/id_14/212.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
"""
Word Search II

Given a 2D board and a list of words from the dictionary, find all words in the board.

Each word must be constructed from letters of sequentially adjacent cell, where "adjacent"
cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.

For example,
Given words = ["oath","pea","eat","rain"] and board =

[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
Return ["eat","oath"].
Note:
You may assume that all inputs are consist of lowercase letters a-z.
"""

# 太慢, 被拒了
class Solution(object):
def isExists(self, board, word, y, x, location):
if len(word) > len(board) * len(board[0]):
return False
if location == len(word):
return True
if y < 0 or x < 0 or y == len(board) or x == len(board[y]):
return False

if board[y][x] != word[location]:
return False
a = ord('#')
board[y][x], a = a, board[y][x]
ret = self.isExists(board, word, y + 1, x, location + 1) \
or self.isExists(board, word, y - 1, x, location + 1) \
or self.isExists(board, word, y, x + 1, location + 1) \
or self.isExists(board,word, y, x - 1, location + 1)
board[y][x], a = a, board[y][x]
return ret
def findWords(self, board, words):
"""
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
if not words:
return []
if not board:
return []
results = []
wordDict = {}
for word in words:
if word in wordDict:
continue

wordDict[word] = 0

for y in range(len(board)):
if wordDict[word] > 0:
continue
for x in range(len(board[0])):
if wordDict[word] > 0:
continue
if self.isExists(board, word, y, x, 0):
wordDict[word] += 1
results.append(word)
if len(results) == len(words):
return results
return results


board = [
['a'],
['a']
]
words = ["a"]

s = Solution()
print(s.findWords(board, words))
52 changes: 52 additions & 0 deletions 3rd/homework_3/id_14/112.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
"""
Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path
such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None

class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if not root:
return False
if root.val == sum and root.left == None and root.right == None:
return True
return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)

sum = 22
root = TreeNode(5)
root.left = TreeNode(4)
root.right = TreeNode(8)
root.left.left = TreeNode(11)
root.left.left.left = TreeNode(7)
root.left.left.right = TreeNode(2)
root.right.left = TreeNode(13)
root.right.right = TreeNode(4)
root.right.right.right = TreeNode(1)

s = Solution()
print(s.hasPathSum(root, sum))


64 changes: 64 additions & 0 deletions 3rd/homework_4/id_14/142.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
"""
Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None

class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
runner = head
walker = head
while runner and runner.next:
walker = walker.next
runner = runner.next.next
if walker == runner:
node = head
while node != walker:
walker = walker.next
node = node.next
return node
return None

class Solution2(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
node = head
nodeSet = set()
while node:
if node in nodeSet:
return node
nodeSet.add(node)
node = node.next
return None

head = ListNode(3)
head.next = ListNode(2)
node = head.next
head.next.next = ListNode(0)
head.next.next.next = ListNode(-4)
head.next.next.next.next = node

s = Solution()
l = s.detectCycle(head)
if l:
print(l.val)
else:
print('Null')
Loading