Leetcode刷题记录-20181020
111.Minimum Depth of Binary Tree
给定一个二叉树,求其最小深度
如果没有根节点,返回0;如果有根节点,判断左右孩子,有左孩子,返回 左孩子最小深度+1;有右孩子,返回右孩子最小深度+1;左右孩子都有,返回左右孩子最小深度+1;都没有,返回1
1 class Solution: 2 def minDepth(self, root): 3 """ 4 :type root: TreeNode 5 :rtype: int 6 """ 7 if not root: 8 return 0 9 a = root.right 10 b = root.left 11 if a and b: 12 return min(self.minDepth(a),self.minDepth(b))+1 13 if a and not b: 14 return self.minDepth(a)+1 15 if not a and b: 16 return self.minDepth(b)+1 17 if not a and not b: 18 return 1
112.Path Sum
寻找二叉树中是否存在一条节点和为给定数值的路径,路径为从根节点到叶子
1 class Solution: 2 def hasPathSum(self, root, sum): 3 """ 4 :type root: TreeNode 5 :type sum: int 6 :rtype: bool 7 """ 8 result = sum 9 if root: 10 p = root.left 11 q = root.right 12 if not p and not q: 13 if result == root.val: 14 return True 15 else: 16 return False 17 if not p: 18 return self.hasPathSum(q,result-root.val) 19 if not q: 20 return self.hasPathSum(p,result-root.val) 21 if p and q: 22 return self.hasPathSum(p,result-root.val) or self.hasPathSum(q,result-root.val) 23 else: 24 return False
杨辉三角形
每层数字列表 = 对([0,上一层数字,0])列表内数据依次相加得到
1 class Solution: 2 def generate(self,numRows): 3 """ 4 :type numRows: int 5 :rtype: List[List[int]] 6 """ 7 result = [] 8 if numRows == 0: 9 return [] 10 if numRows >=1: 11 result.append([1]) 12 13 14 for i in range(1,numRows): 15 if i == 0: 16 result.append([1]) 17 temp = result[-1] 18 temp = [0] + temp 19 temp.append(0) 20 each_level = [] 21 for j in range(len(temp)-1): 22 each_level.append(temp[j]+temp[j+1]) 23 result.append(each_level) 24 return result