Sum Root to Leaf Numbers——LeetCode

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之间的数字,从根节点到叶结点表示一个数字,求所有的这些数字的和。

解题思路:这道题应该是考察DFS,可以直接DFS求解,或者中序遍历用queue也可以做,最近做题没什么状态,脑袋一团浆糊。

    public int sumNumbers(TreeNode root) {

        return sum(root,0);

    }

    

    public int sum(TreeNode node,int sum){

        if(node==null){

            return 0;

        }

        if(node.left==null&&node.right==null){

            sum=sum*10+node.val;

            return sum;

        }

           return  sum(node.left,sum*10+node.val)+sum(node.right,sum*10+node.val);

    }

 

你可能感兴趣的:(LeetCode)