题目:
给定一棵二叉树,二叉树的每个节点只包含0-9这10个数字。将该树从根节点读到叶节点组成一个整数。返回读到的所有整数之和。
解题思路:
通过递归读取树的各个节点(中序遍历)。
代码(Python):
# 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 sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
list_num = []
def Iteration(root,str0):
if root==None:
return 0
if root.left==None and root.right==None:
list_num.append(str0+str(root.val))
elif root.left==None and root.right!=None:
Iteration(root.right,str0+str(root.val))
elif root.left!=None and root.right==None:
Iteration(root.left,str0+str(root.val))
elif root.left!=None and root.right!=None:
Iteration(root.left,str0+str(root.val))
Iteration(root.right,str0+str(root.val))
Iteration(root,'')
print list_num
output = 0
for i in list_num:
output = output+int(i)
return output