LeetCode 129. Sum Root to Leaf Numbers 根到叶子节点数字之和(Java)

题目:

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.

Note: A leaf is a node with no children.
LeetCode 129. Sum Root to Leaf Numbers 根到叶子节点数字之和(Java)_第1张图片

解答:

本题即为一道前序遍历的过程。思路如下:

  1. 当遍历到非叶子节点时,记录当前路径的值num,并继续递归其左右子节点。其中,当前路径的值即为:之前路径值 num + 当前节点值
  2. 当遍历到叶子节点时,将当前路径值加至最终结果 sum 中

代码实现如下:

class Solution {
    int sum = 0;
    public int sumNumbers(TreeNode root) {
        sumToLeaf(root, 0);
        return sum;
    }
    private void sumToLeaf(TreeNode node, int num){
        if(node == null) {
            return;
        }
        num = num * 10 + node.val;
        if(node.left == null && node.right == null) {
            sum += num;
        }
        sumToLeaf(node.left, num);
        sumToLeaf(node.right, num);
    }
}

你可能感兴趣的:(LeetCode)