文章目录
- 前文
- 94. Binary Tree Inorder Traversal
- 95. Unique Binary Search Trees II
- 96. Unique Binary Search Trees
- Validate Binary Search Tree
- 102. Binary Tree Level Order Traversal
- 103. Binary Tree Zigzag Level Order Traversal
- 105. Construct Binary Tree from Preorder and Inorder Traversal
- 116. Populating Next Right Pointers in Each Node
- 129. Sum Root to Leaf Numbers
- 199. Binary Tree Right Side View
- 236. Lowest Common Ancestor of a Binary Tree
- 总结
前文
继上篇Leetcode题Leetcode题Stack,我们开始分享Tree系列的题,照旧是前300的题,并且重复系列的跳过。
94. Binary Tree Inorder Traversal
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
"""
题目是求树的中序遍历:即左->根->右,通过queue队列完成
首先求出树的最左子树,然后从最左子树开始后的每个节点,分别求每个node的左子树和右子树,则构成左->根->右
Runtime: 36 ms, faster than 71.51% of Python3 online submissions for Binary Tree Inorder Traversal.
Memory Usage: 13.8 MB, less than 6.56% of Python3 online submissions for Binary Tree Inorder Traversal.
"""
def inorderTraversal(self, root: TreeNode) -> List[int]:
res, stack = [], []
while True:
while root:
stack.append(root)
root = root.left
if not stack:
return res
node = stack.pop()
res.append(node.val)
root = node.right
95. Unique Binary Search Trees II
# 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):
"""
题意是列出给出的数字范围内的所有BST集合
利用树的迭代完成
Runtime: 44 ms, faster than 48.10% of Python online submissions for Unique Binary Search Trees II.
Memory Usage: 15.6 MB, less than 27.68% of Python online submissions for Unique Binary Search Trees II.
"""
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
if n == 0:
return []
return self.dfs(1, n+ 1)
def dfs(self, start, end):
if start == end:
return None
result = []
for i in range(start, end):
for l in self.dfs(start, i) or [None]:
for r in self.dfs(i + 1, end) or [None]:
node = TreeNode(i)
node.left, node.right = l, r
result.append(node)
return result
96. Unique Binary Search Trees
class Solution(object):
"""
题意是相对95题只需拿到拥有多少组BST即可
用了记忆递归,即定义了map,如果存在该键值,则直接取值即可
解法以i为根节点,比i小的数1...i-1作为左子树,比i大的数i+1...n作为右子树,左子树的排列和右子树的排列的乘积是此时的数目。
Runtime: 20 ms, faster than 46.81% of Python online submissions for Unique Binary Search Trees.
Memory Usage: 11.7 MB, less than 56.49% of Python online submissions for Unique Binary Search Trees.
"""
def __init__(self):
self.dp = dict()
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
if n in self.dp:
return self.dp[n]
if n == 0 or n == 1:
return 1
ans = 0
for i in range(1, n + 1):
ans += self.numTrees(i - 1) * self.numTrees(n - i)
self.dp[n] = ans
return ans
class Solution2(object):
"""
动态规划解法,参考博文:https://blog.csdn.net/fuxuemingzhu/article/details/79367789
Runtime: 12 ms, faster than 90.35% of Python online submissions for Unique Binary Search Trees.
Memory Usage: 11.8 MB, less than 47.40% of Python online submissions for Unique Binary Search Trees.
"""
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
dp = [1, 1]
for i in range(2, n + 1):
count = 0
for j in range(i):
count += dp[j] * dp[i - j - 1]
dp.append(count)
return dp.pop()
Validate Binary Search Tree
# 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):
"""
题意是验证一棵树是否为BST,BST满足左子树小于根小于右子树,所以中序遍历后必然是有序的
先中序遍历,然后判断是否是有序的即可
Runtime: 32 ms, faster than 83.45% of Python online submissions for Validate Binary Search Tree.
Memory Usage: 16.7 MB, less than 25.77% of Python online submissions for Validate Binary Search Tree.
"""
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
output = []
self.inOrder(root ,output)
for i in range(1 ,len(output)):
if output[i] <= output[ i -1]:
return False
return True
def inOrder(self ,root ,output):
if not root:
return None
self.inOrder(root.left, output)
output.append(root.val)
self.inOrder(root.right, output)
102. Binary Tree Level Order Traversal
# 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):
"""
题意求一棵树的层级遍历,通过BFS来完成
queue的概念用deque来实现,popleft() 时间复杂为O(1)即可
外围的While用来定义BFS的终止条件,所以我们最开始initialize queue的时候可以直接把root放进去
在每层的时候,通过一个cur_level记录当前层的node.val,size用来记录queue的在增加子孙node之前大小,因为之后我们会实时更新queue的大小。
当每次从queue中pop出来的节点,把它的左右子节点放进Queue以后,记得把节点本身的的value放进cur_level
for loop终止后,就可以把记录好的整层的数值,放入我们的return数组里。
Runtime: 16 ms, faster than 95.21% of Python online submissions for Binary Tree Level Order Traversal.
Memory Usage: 12.2 MB, less than 88.00% of Python online submissions for Binary Tree Level Order Traversal.
"""
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
from collections import deque
if not root :return []
queue ,res = deque([root]) ,[]
while queue:
cur_level, size = [], len(queue)
for i in range(size):
node = queue.popleft()
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
cur_level.append(node.val)
res.append(cur_level)
return res
class Solution2(object):
"""
DFS遍历
Runtime: 20 ms, faster than 79.17% of Python online submissions for Binary Tree Level Order Traversal.
Memory Usage: 12.5 MB, less than 22.06% of Python online submissions for Binary Tree Level Order Traversal.
"""
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
res = []
self.dfs(root, 0, res)
return res
def dfs(self, root, level, res):
if not root:
return
if len(res) < level+1:
res.append([])
res[level].append(root.val)
self.dfs(root.left, level+1, res)
self.dfs(root.right, level+1, res)
103. Binary Tree Zigzag Level Order Traversal
# 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):
"""
题意是求树从根节点到叶节点之间的路径和等于所给的sum值的所有集合
利用dfs即递归回溯算法完成
Runtime: 40 ms, faster than 43.75% of Python online submissions for Path Sum II.
Memory Usage: 18 MB, less than 68.85% of Python online submissions for Path Sum II.
"""
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
if not root: return []
res = []
self.dfs(root, sum, res, [root.val])
return res
def dfs(self, root, target, res, path):
if not root: return
if sum(path) == target and not root.left and not root.right:
res.append(path)
if root.left:
self.dfs(root.left, target, res, path + [root.left.val])
if root.right:
self.dfs(root.right, target, res, path + [root.right.val])
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution2(object):
"""
同样的可以用BFS来完成,即每次都把每一层的所有结果放入
Runtime: 48 ms, faster than 13.69% of Python online submissions for Path Sum II.
Memory Usage: 14.2 MB, less than 86.49% of Python online submissions for Path Sum II.
"""
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
if not root:
return []
res = []
queue = [(root, root.val, [root.val])]
while queue:
curr, val, ls = queue.pop(0)
if not curr.left and not curr.right and val == sum:
res.append(ls)
if curr.left:
queue.append((curr.left, val + curr.left.val, ls + [curr.left.val]))
if curr.right:
queue.append((curr.right, val + curr.right.val, ls + [curr.right.val]))
return res
105. Construct Binary Tree from Preorder and Inorder Traversal
# 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):
"""
题意是将BST原地转化为单右边树,解题思路是递归将左子树全部转化为右子树,然后再将右子树全部转化为最右边树
详细图解如下,要注意的是每次遍历到左子树也节点后,就会返回然后走右子树,然后将此时的root.right=left,
即图解的第三步,因为此时root.right=left,所以要判断left的右子树是否结束,即用while来循环将left走完,最后
再赋值回右子树
1
\
2 5
\ \
3 4 6
1
\
2 5
\ \
3 4 6
1
\
2 5
\ \
3 6
\
4
1
\
2
\
3
\
4
\
5
\
6
Runtime: 16 ms, faster than 96.41% of Python online submissions for Flatten Binary Tree to Linked List.
Memory Usage: 12.1 MB, less than 73.53% of Python online submissions for Flatten Binary Tree to Linked List.
"""
def flatten(self, root):
"""
:type root: TreeNode
:rtype: None Do not return anything, modify root in-place instead.
"""
if not root: return
left = root.left
right = root.right
root.left = None
self.flatten(left)
self.flatten(right)
root.right = left
while root.right:
root = root.right
root.right = right
class Solution2(object):
"""
取巧的方法,即先前序遍历,然后直接在列表里修改
Runtime: 24 ms, faster than 62.28% of Python online submissions for Flatten Binary Tree to Linked List.
Memory Usage: 12.1 MB, less than 72.00% of Python online submissions for Flatten Binary Tree to Linked List
"""
def flatten(self, root):
"""
:type root: TreeNode
:rtype: None Do not return anything, modify root in-place instead.
"""
res = []
self.preOrder(root, res)
for i in range(len(res) - 1):
res[i].left = None
res[i].right = res[i + 1]
def preOrder(self, root, res):
if not root: return
res.append(root)
self.preOrder(root.left, res)
self.preOrder(root.right, res)
116. Populating Next Right Pointers in Each Node
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, left, right, next):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution(object):
"""
题意是将完全二叉树转为每层的链表,
解法通过两个判断,第一个判断是否有右子树,如果有则左子树指向右子树;第二个判断本身是否指向下一个,如果有,
则需要把右子树再指向本身下一个的左子树,按题来说就是先2->3,然后5->6
"""
def connect(self, root):
"""
:type root: Node
:rtype: Node
"""
if not root: return
if root.right:
root.left.next = root.right
if root.next:
root.right.next = root.next.left
self.connect(root.left)
self.connect(root.right)
class Solution2(object):
"""
Runtime: 52 ms, faster than 75.03% of Python online submissions for Populating Next Right Pointers in Each Node.
Memory Usage: 14.1 MB, less than 84.00% of Python online submissions for Populating Next Right Pointers in Each Node.
"""
def connect(self, root):
"""
:type root: Node
:rtype: Node
"""
if root is None:
return None
queue = [root]
while queue:
level = queue
queue = []
while level:
node = level.pop(0)
if not level:
node.next = None
else:
node.next = level[0]
if node.left != None:
queue.append(node.left)
if node.right != None:
queue.append(node.right)
return root
129. Sum Root to Leaf Numbers
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
"""
题意是求树每条路径的和,而每条路径得到的数就是从根到叶节点
用dfs实现,整体思路和113 path sum一致,不过这里的path和是利用value*10+node.right/left.value的值
Runtime: 36 ms, faster than 86.76% of Python3 online submissions for Sum Root to Leaf Numbers.
Memory Usage: 14 MB, less than 5.55% of Python3 online submissions for Sum Root to Leaf Numbers.
"""
def sumNumbers(self, root: TreeNode) -> int:
if not root:return 0
stack,res = [(root,root.val)],0
while stack:
node,value = stack.pop()
if not node.left and not node.right:
res += value
if node.right:
stack.append((node.right, value*10+node.right.val))
if node.left:
stack.append((node.left, value*10+node.left.val))
return res
class Solution2:
"""
BFS,但感觉只是用queue重新实现了DFS,区别不大
Runtime: 40 ms, faster than 58.70% of Python3 online submissions for Sum Root to Leaf Numbers.
Memory Usage: 14.1 MB, less than 5.55% of Python3 online submissions for Sum Root to Leaf Numbers.
"""
def sumNumbers(self, root: TreeNode) -> int:
if not root:
return 0
queue, res = collections.deque([(root, root.val)]), 0
while queue:
node, value = queue.popleft()
if node:
if not node.left and not node.right:
res += value
if node.left:
queue.append((node.left, value*10+node.left.val))
if node.right:
queue.append((node.right, value*10+node.right.val))
return res
class Solution3:
"""
Runtime: 40 ms, faster than 58.70% of Python3 online submissions for Sum Root to Leaf Numbers.
Memory Usage: 14.1 MB, less than 5.55% of Python3 online submissions for Sum Root to Leaf Numbers.
"""
def sumNumbers(self, root: TreeNode) -> int:
self.res = 0
self.dfs(root, 0)
return self.res
def dfs(self, root, value):
if root:
# if not root.left and not root.right:
# self.res += value*10 + root.val
self.dfs(root.left, value * 10 + root.val)
# if not root.left and not root.right:
# self.res += value*10 + root.val
self.dfs(root.right, value * 10 + root.val)
if not root.left and not root.right:
self.res += value * 10 + root.val
199. Binary Tree Right Side View
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
"""
题意是从右边看一棵树,返回你能看到的全部
递归实现,要考虑几种情况:
1.最左边左子树高于右子树,则要先返回最左边左子树
2.最右边右子树下的左子树高于右子树
3.右子树或者左子树刚好成一排
解法:先得到最右、最左子树,然后返回结果:root.val+右子树+多出的左子树
Runtime: 36 ms, faster than 83.42% of Python3 online submissions for Binary Tree Right Side View.
Memory Usage: 13.8 MB, less than 5.26% of Python3 online submissions for Binary Tree Right Side View.
"""
def rightSideView(self, root: TreeNode) -> List[int]:
if not root:
return []
right = self.rightSideView(root.right)
left = self.rightSideView(root.left)
return [root.val] + right + left[len(right):]
class Solution2:
"""
DFS解法,可以说非常巧妙了,核心就在于depth == len(view)
通过这个条件牢牢把握上述的三种情况,当左子树低于最右边时,即不满足depth==len(view)
而每当遍历到的节点,depth高于当前的depth:即len(view),就添加到结果集,因为递归是从右到左,
所以肯定会从右到左的加入节点
"""
def rightSideView(self, root: TreeNode) -> List[int]:
def collect(node, depth):
if node:
if depth == len(view):
view.append(node.val)
collect(node.right, depth+1)
collect(node.left, depth+1)
view = []
collect(root, 0)
return view
236. Lowest Common Ancestor of a Binary Tree
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
"""
题意是求树的最小祖先,即两个节点最靠近叶子节点的祖先,如果两个节点是同一颗子树,则祖先是其中的一个节点
解法直接递归求左子树和右子树,如果两者同时存在,则说明祖先是二者的父节点。如果左子树存在,右子树不存在,则
祖先就是左子树对应的root。
要注意的是递归终止条件,即当root==p or root==q就说明找到了对应的节点,而not root也返回root,则说明没有找到,
此时返回的root即是None
"""
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root or root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root
return left or right
总结
本次树的分享到此为止,下次继续分享leetcode~