Sum Root to Leaf Numbers (Java)

来源:互联网 发布:人工智能发明成果 编辑:程序博客网 时间:2024/06/10 07:16

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.


Source

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    int sum = 0;    public int sumNumbers(TreeNode root) {    if(root == null) return 0;        int va = 0;    dfs(root, va);        return sum;    }        public void dfs(TreeNode root, int va){    if(root.left == null && root.right == null){    sum = sum + va *10 + root.val;    //到根节点才开始加    }        va = va * 10 + root.val;    if(root.left != null)  dfs(root.left, va);    if(root.right != null)  dfs(root.right, va);    }}


Test

 public static void main(String[] args){    TreeNode a = new TreeNode(1);    a.left = new TreeNode(2);    a.right = new TreeNode(3);        System.out.println(new Solution().sumNumbers(a));    }


0 0
原创粉丝点击