leetcode----129. Sum Root to Leaf Numbers

链接:

https://leetcode.com/problems/sum-root-to-leaf-numbers/

大意:

给定一棵树根节点root,求出从根节点到每个叶子节点路径上数字组成的十进制数的和。例子:

思路:

先序遍历,回溯。

遍历到一个节点时, 首先计算根节点到该节点路径上数字组成的十进制数,再判断当前节点是否为叶子节点即可。

函数外部保存一个变量sum用于记录根节点到每个叶子节点路径上数字组成的十进制数字的和。

代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int sum = 0;
    public int sumNumbers(TreeNode root) {
        if (root == null)
            return 0;
        dfs(root, 0);
        return sum;
    }
    private void dfs(TreeNode root, int val) {
        val = val * 10 + root.val;
        // 叶子节点
        if (root.left == null && root.right == null) {
            sum += val;
            return ;
        }
        if (root.left != null)
            dfs(root.left, val);
        if (root.right != null)
            dfs(root.right, val);
    }
}

结果:

结论:

很简单的一个回溯题。 

 

猜你喜欢

转载自blog.csdn.net/smart_ferry/article/details/89325867