Sum Root to Leaf Numbers

来源:互联网 发布:strpos php 编辑:程序博客网 时间:2024/06/16 00:57

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.

思路 : Using  In order to traverse the whole tree.

易错点:  注意要先判断 root  是否叶子节点 再加,  否则用直接判断 root  == null 的方法 会多 重复计算一次

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int sumNumbers(TreeNode root) {        int[] ret = new int[1];        if(root == null)            return ret[0];        inOrder(0, root, ret);        return ret[0];    }        private void inOrder(int n, TreeNode root, int[] ret){        if(root.left == null && root.right == null){            ret[0] += n * 10 + root.val;            return;        }        if(root.left != null)            inOrder(n * 10 + root.val, root.left, ret);        if(root.right != null)            inOrder(n * 10 + root.val, root.right, ret);    }}


0 0
原创粉丝点击