leetcode129 Sum Root to Leaf Numbers
Posted yawenw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode129 Sum Root to Leaf Numbers相关的知识,希望对你有一定的参考价值。
1 """ 2 Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. 3 An example is the root-to-leaf path 1->2->3 which represents the number 123. 4 Find the total sum of all root-to-leaf numbers. 5 Note: A leaf is a node with no children. 6 Example: 7 Input: [1,2,3] 8 1 9 / 10 2 3 11 Output: 25 12 Explanation: 13 The root-to-leaf path 1->2 represents the number 12. 14 The root-to-leaf path 1->3 represents the number 13. 15 Therefore, sum = 12 + 13 = 25. 16 Example 2: 17 Input: [4,9,0,5,1] 18 4 19 / 20 9 0 21 / 22 5 1 23 Output: 1026 24 Explanation: 25 The root-to-leaf path 4->9->5 represents the number 495. 26 The root-to-leaf path 4->9->1 represents the number 491. 27 The root-to-leaf path 4->0 represents the number 40. 28 Therefore, sum = 495 + 491 + 40 = 1026. 29 """ 30 """ 31 本题两种解法 32 第一种为递归 33 """ 34 35 class TreeNode: 36 def __init__(self, x): 37 self.val = x 38 self.left = None 39 self.right = None 40 41 class Solution1: 42 def sumNumbers(self, root): 43 self.res = 0 # !!!res申请为全局变量,保存总的结果 44 self.sum(root, 0) # !!!第一次传0值是为了递归的时候传入正确的根结点值 45 return self.res 46 47 def sum(self, root, value): 48 if root: 49 if root.left == None and root.right == None: # !!!判断叶子结点 50 self.res += 10 * value + root.val 51 self.sum(root.left, 10 * value + root.val) 52 self.sum(root.right, 10 * value + root.val) 53 54 """ 55 非递归的写法,先用tuple存储(value, root) 56 然后入队列遍历 57 """ 58 59 class Solution2: 60 def sumNumbers(self, root): 61 res = 0 62 if root == None: 63 return res 64 queue = [] 65 x = (0, root) # tuple元组,(父亲结点的值,结点) 66 queue.append(x) 67 while queue: 68 value, node = queue.pop() # 头结点出队 69 if node: 70 if not node.left and not node.right: # 判断叶子结点,加各个路径的和 71 res = res + node.val + value * 10 72 queue += [(node.val + 10 * value, node.left), (node.val + 10 * value, node.right)] 73 # 层次遍历 也可以用queue.extend([(, ), (, )])来写 74 return res
以上是关于leetcode129 Sum Root to Leaf Numbers的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 129. Sum Root to Leaf Numbers
[leetcode-129-Sum Root to Leaf Numbers]
leetcode129 Sum Root to Leaf Numbers
[LeetCode129]Sum Root to Leaf Numbers