129. Sum Root to Leaf Numbers

2019-02-13  本文已影响0人  丶沧月

题目描述

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

给定仅包含0-9的数字的二叉树,每个根到叶路径可以表示数字。

An example is the root-to-leaf path 1->2->3 which represents the number 123.

一个例子是根到叶路径1-> 2-> 3,它代表数字123。

Find the total sum of all root-to-leaf numbers.

找到所有根到叶数的总和。

Note: A leaf is a node with no children.

注意:叶子是没有子节点的节点。

Example:

Input: [1,2,3]
    1
   / \
  2   3
Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.

Example 2:

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.

思路与实现

递归(DFS)

class Solution {
    public int sumNumbers(TreeNode root) {
        return dfs(root, 0);
    }
    
    private int dfs(TreeNode node, int sum) {
        
        if (node == null) {
            return 0;
        }
        
        if (node.left == null && node.right == null) {
            return sum += node.val;
        }
        
        int next = (sum + node.val)*10;
        int leftSum = dfs(node.left, next);
        int rightSum = dfs(node.right, next);
        
        return leftSum + rightSum;
        
    }
}
上一篇 下一篇

猜你喜欢

热点阅读