8.1刷题
- 找两个节点的最近公共祖先
- 二叉搜索树,如果root的值在两个节点之间,那么说明root即为公共祖先,返回root,如果两个节点的值都小于root,那么递归去root的左子树,否则右子树
- 普通树,递归分别去左子树右子树找输入的两个节点,如果在左子树没有找到,说明两个节点都在右子树
二叉搜索树代码
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root or not p or not q:
return 0
if root.val >= p.val and root.val <=q.val:
return root
elif root.val>p.val and root.val>q.val:
return self.lowestCommonAncestor(root.left,p,q)
else:
return self.lowestCommonAncestor(root.right,p,q)
普通树代码
class Solution:
def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
if not root:
return None
if root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left,p,q)
right = self.lowestCommonAncestor(root.right,p,q)
return root if left and right else left or right
- n个骰子的点数
思路:动态规划
代码:
class Solution:
def dicesProbability(self, n: int) -> List[float]:
dp = [1/6]*6
for i in range(2,n+1):
tmp = [0] *(5*i+1)
for j in range(len(dp)):
for k in range(6):
tmp[j+k] += dp[j]/6
dp = tmp
return dp