617. Merge Two Binary Trees
Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.
Example 1:
Input:
Tree 1
1
/ \
3 2
/
5
Tree 2
2
/ \
1 3
\ \
4 7
Output:
Merged tree:
3
/ \
4 5
/ \ \
5 4 7
Note: The merging process must start from the root nodes of both trees.
思路:DFS
class Solution:
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
def dfs(r1, r2):
r = None
if r1 and not r2:
r = TreeNode(r1.val)
r.left = dfs(r1.left, None)
r.right = dfs(r1.right, None)
elif r2 and not r1:
r = TreeNode(r2.val)
r.left = dfs(None, r2.left)
r.right = dfs(None, r2.right)
elif r1 and r2:
r = TreeNode(r1.val + r2.val)
r.left = dfs(r1.left, r2.left)
r.right = dfs(r1.right, r2.right)
return r
return dfs(t1, t2)
Beat 25.93% python3 2018-05-26
优化:复用空间
class Solution:
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
if not t2:
return t1
if not t1:
return t2
t2.val += t1.val
t2.left = self.mergeTrees(t1.left, t2.left)
t2.right = self.mergeTrees(t1.right, t2.right)
return t2
Beat 98.31% python3 2018-05-26
572. Subtree of Another Tree
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node’s descendants. The tree s could also be considered as a subtree of itself.
Example 1:
Given tree s:
3
/ \
4 5
/ \
1 2
Given tree t:
4
/ \
1 2
Return true, because t has the same structure and node values with a subtree of s.
Example 2:
Given tree s:
3
/ \
4 5
/ \
1 2
/
0
Given tree t:
4
/ \
1 2
Return false.
常规思路:DFS
class Solution:
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
if s is None:
return t is None
if self.isSameTree(s, t):
return True
return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
def isSameTree(self, s, t):
if s is None:
return t is None
if t is None:
return s is None
return s.val == t.val and self.isSameTree(s.left, t.left) and self.isSameTree(s.right, t.right)
Beat 64.45% python3 2018-05-26
其他思路:表示成字符串,字符串比较
class Solution:
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
def dfs(node):
if not node:
return '$'
return '(' + str(node.val) + ')' + dfs(node.left) + dfs(node.right)
return dfs(t) in dfs(s)
Beat 99.61% python3 2018-05-26
538. Convert BST to Greater Tree
Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.
Example:
Input: The root of a Binary Search Tree like this:
5
/ \
2 13
Output: The root of a Greater Tree like this:
18
/ \
20 13
思路:右-根-左遍历,记录当前值,加到遍历到的节点上
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def convertBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
self.current = 0
def dfs(node):
if node is None:
return
dfs(node.right)
node.val += self.current
self.current = node.val
dfs(node.left)
dfs(root)
return root
Beat 99.05% python3 2018-05-26
注:多次提交时间不同
448. Find All Numbers Disappeared in an Array
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]
思路:从第一个数开始,碰到nums[i] != i+1则找nums[i]位置,早晚找到相同为止,最后遍历,依然nums[i] != i+1的为缺失的数字
class Solution:
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
for i in range(len(nums)):
if nums[i] != i+1:
x = nums[i]
while nums[x-1] != x:
y = nums[x-1]
nums[x-1] = x
x = y
ans = []
for i in range(len(nums)):
if nums[i] != i+1:
ans.append(i+1)
return ans
Beat 58.10% python3 2018-05-26
思路:比较巧的方法
class Solution:
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
length = len(nums)
for n in nums:
nums[(n-1) % length] += length
ans = []
for i, n in enumerate(nums):
if n <= length:
ans.append(i+1)
return ans
Beat 85.44% python3 2018-05-26
思路:使用额外空间
class Solution:
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
length = len(nums)
m = [0] * (length+1)
for n in nums:
m[n] = 1
ans = []
for i in range(1, length+1):
if m[i] == 0:
ans.append(i)
return ans
Beat 100.0% python3 2018-05-26
438. Find All Anagrams in a String
Given a string s and a non-empty string p, find all the start indices of p’s anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
The order of output does not matter.
Example 1:
Input:
s: “cbaebabacd” p: “abc”
Output:
[0, 6]
Explanation:
The substring with start index = 0 is “cba”, which is an anagram of “abc”.
The substring with start index = 6 is “bac”, which is an anagram of “abc”.
Example 2:
Input:
s: “abab” p: “ab”
Output:
[0, 1, 2]
Explanation:
The substring with start index = 0 is “ab”, which is an anagram of “ab”.
The substring with start index = 1 is “ba”, which is an anagram of “ab”.
The substring with start index = 2 is “ab”, which is an anagram of “ab”.
思路:记录p每个字母出现的次数,遍历s,若等长的子串字母出现次数等于p,则为一个所求的解
class Solution:
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
if len(s) < len(p):
return []
ms = [0] * 26
mp = [0] * 26
for i in range(len(p)):
mp[ord(p[i]) - ord('a')] += 1
ms[ord(s[i]) - ord('a')] += 1
ans = []
if ms == mp:
ans.append(0)
j = 0
for i in range(len(p), len(s)):
ms[ord(s[i]) - ord('a')] += 1
ms[ord(s[j]) - ord('a')] -= 1
j += 1
if ms == mp:
ans.append(j)
return ans
Beat 96.23% python3 2018-05-26
思路:使用字典
class Solution:
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
if len(s) < len(p):
return []
ds = dict.fromkeys('abcdefghijklmnopqrstuvwxyz', 0)
dp = dict.fromkeys('abcdefghijklmnopqrstuvwxyz', 0)
for i in range(len(p)):
dp[p[i]] += 1
ds[s[i]] += 1
ans = []
j = 0
if ds == dp:
ans.append(j)
for i in range(len(p), len(s)):
ds[s[i]] += 1
ds[s[j]] -= 1
j += 1
if ds == dp:
ans.append(j)
return ans
Beat 100.0% python3 2018-05-26