LeetCode 129. Sum Root to Leaf Numbers
2020-05-20 21:42:40
# leetcode
Problem
LeetCode 129. Sum Root to Leaf Numbers
1. 题目简述
给出一棵只含有value值为0-9的二叉树,根节点为root,每一条从root到leaf节点的路径都代表一个数字,求这些所有数字之和。例如:
Input: [4,9,0,5,1]
4
/ \
9 0
/ \
5 1
Output: 1026
Explanation:
The root-to-leaf path 4->9->5 represents the number 495.
The root-to-leaf path 4->9->1 represents the number 491.
The root-to-leaf path 4->0 represents the number 40.
Therefore, sum = 495 + 491 + 40 = 1026.
2. 算法思路
DFS
很简单的DFS的思路,前序遍历的思路,到达根节点时做一次判断。
3. 解法
1 | /** |