4
头图

Find the sum of the numbers from the root node to the leaf node

Title description: Give you the root node root of a binary tree. Each node in the tree stores a number between 0 and 9.
Each path from the root node to the leaf node represents a number:

  • For example, the path 1 -> 2 -> 3 from the root node to the leaf node represents the number 123.
    Calculate the sum of all the numbers generated from the root node to the leaf node.

Leaf nodes are nodes that have no child nodes.

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution one: recursive method

Use recursion to solve this problem, the recursive process is as follows:

  • First of all, if the current node is null, it means it is an empty tree and return directly;
  • If the current node is not nll, add the value of the current node to path;
  • Then judge that the current node has no left or right child nodes, indicating that it is a leaf node, add the current path value to the result, and then return;
  • If the left node of the current node is not empty, the left node is processed recursively;
  • If the right node of the current node is not empty, the right node is processed recursively.

Finally, return result is the result value.

import com.kaesar.leetcode.TreeNode;

public class LeetCode_129 {
    // 最终的累加值
    private static int result = 0;

    public static int sumNumbers(TreeNode root) {
        sumNumbers(root, "");
        return result;
    }

    /**
     * 递归法
     *
     * @param root
     * @param path
     */
    private static void sumNumbers(TreeNode root, String path) {
        // 如果当前节点为null,说明是空树,直接返回
        if (root == null) {
            return;
        }
        // 将当前节点的值添加到 path 中
        path += root.val;
        // 如果当前节点没有左右子节点,说明是叶子节点,将当前的路径值加到result中,然后返回
        if (root.left == null && root.right == null) {
            result += Integer.valueOf(path);
            return;
        }
        if (root.left != null) {
            // 当前节点的左节点不为空时,递归处理左节点
            sumNumbers(root.left, path);
        }
        if (root.right != null) {
            // 当前节点的右节点不为空时,递归处理右节点
            sumNumbers(root.right, path);
        }
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(4);
        root.left = new TreeNode(9);
        root.right = new TreeNode(0);
        root.left.left = new TreeNode(5);
        root.left.right = new TreeNode(1);

        // 测试用例,期望输出: 1026
        System.out.println(sumNumbers(root));
    }
}
[Daily Message] Life is like a gambling game. It is impossible to win all of them. As long as the chips are in your hands, there will always be hope.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!