1022.Sum of Root To Leaf Binary Numbers(从根到叶的二进制数之和)

Description

Given a binary tree, each node has value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13.

For all leaves in the tree, consider the numbers represented by the path from the root to that leaf.

Return the sum of these numbers.


给出一棵二叉树,其上每个结点的值都是 01 。每一条从根到叶的路径都代表一个从最高有效位开始的二进制数。例如,如果路径为 0 -> 1 -> 1 -> 0 -> 1,那么它表示二进制数 01101,也就是 13

对树上的每一片叶子,我们都要找出从根到该叶子的路径所表示的数字。

10^9 + 7 为模,返回这些数字之和。

题目链接:https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/

Difficulty: easy

Example 1:

sum-of-root-to-leaf-binary-numbers.png

Input: [1,0,1,0,1,0,1]
Output: 22
Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22

Note:

  • The number of nodes in the tree is between 1 and 1000.
  • node.val is 0 or 1.
  • The answer will not exceed 2^31 - 1.

分析

  • 定义getSum(root,s=0)函数用于得到以root为根节点的二叉树表示的二进制之和;
  • s表示遍历到当前节点,之前的父节点表示的数,若root=None,返回0,此路不通;
  • 反之,node记录左右子树的结果和,s(s=s*2+root.val)更新,若node=0,返回s,反之返回node;
  • 返回getSum(root),s默认零。

参考代码

#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):
def sumRootToLeaf(self, root):
    def getSum(root,s=0):
        if(root == None):
            return 0
        else:
            s=s*2+root.val
            node=0
            if(root.left):
                node+=getSum(root.left,s)
            if(root.right):
                node+=getSum(root.right,s)
            return s if node==0 else node
    return getSum(root)
-------------本文结束你这么美,还坚持读完了-------------