Leetcode刷題記錄-20181020
阿新 • • 發佈:2018-11-09
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 ifView Codenot 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 17if 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: boolView Code7 """ 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 resultView Code