Sum Root to Leaf Numbers

2019-12-03  本文已影响0人  瞬铭

https://leetcode.com/problems/sum-root-to-leaf-numbers/
给定一个二叉树,求根节点到叶子节点的数字组成的所有十进制整数的和
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.

题解

类似path sum,用DFS求解

  /**
     * @param root
     * @return
     */
      public int sumNumbersDFS(TreeNode root, int sum) {
        if (root == null) {
            return 0;
        }

        //父节点的和值
        //父节点的值扩大10倍后加上该节点的val
        sum = sum * 10 + root.val;

        //此节点是叶子节点,直接返回,不进行处理
        if (root.left == null && root.right == null) {
            return sum;
        }

        int leftSum = sumNumbersDFS(root.left, sum);

        int rightSum = sumNumbersDFS(root.right, sum);

        return leftSum + rightSum;
    }
上一篇下一篇

猜你喜欢

热点阅读