Leetcode 129. Sum Root to Leaf N

作者: ShutLove | 来源:发表于2017-10-20 16:48 被阅读4次

    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的数字,从根节点到叶子节点可以看做是一个数字,求所有数字的和。

    思路:用深度优先搜索求出每个根节点到叶子节点代表的数字,最后求和即可。

    public int res = 0;
    
    public int sumNumbers(TreeNode root) {
        if (root == null) {
            return res;
        }
    
        dfs(root, 0);
    
        return res;
    }
    
    private void dfs(TreeNode node, int curSum) {
        curSum = curSum * 10 + node.val;
    
        if (node.left == null && node.right == null) {
            res += curSum;
            return;
        }
    
        if (node.left != null) {
            dfs(node.left, curSum);
        }
    
        if (node.right != null) {
            dfs(node.right, curSum);
        }
    }

    相关文章

      网友评论

        本文标题:Leetcode 129. Sum Root to Leaf N

        本文链接:https://www.haomeiwen.com/subject/ytmvuxtx.html