Middle-题目46:129. Sum Root to Leaf Numbers

题目原文:
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
For example,

    1
   / \   2   3

The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Return the sum = 12 + 13 = 25.
题目大意:
有一个二叉树,节点是0-9构成的数字,这样从根节点到叶子节点的每一条路径构成一个数,计算所有路径上的数的和。
题目分析:
本题就是一个记忆化的前序遍历,一直记录着前面的数,每次向孩子搜索的时候把当前数×10加上当前节点的数,搜到叶子节点的时候加到当前的和里面。
源码:(language:java)

public class Solution {
    private int currentTotal = 0;
    public int sumNumbers(TreeNode root) {
       dfs(root,0);
       return currentTotal;
    }
    private void dfs(TreeNode node, int currentSum) {
        if(node == null)
            return;
        else if(isLeaf(node)) {
            currentSum+=node.val;
            currentTotal+=currentSum;
        }
        else {
            currentSum+=node.val;
            dfs(node.left,currentSum*10);
            dfs(node.right,currentSum*10);
        }
    }
    private boolean isLeaf(TreeNode node) {
        return node.left==null && node.right==null;
    }
}

成绩:
1ms,beats 28.93%,众数1ms,60.87%

你可能感兴趣的:(Middle-题目46:129. Sum Root to Leaf Numbers)