欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Leetcode 129. 求根到叶子节点数字之和

程序员文章站 2022-04-30 19:14:48
129. 求根到叶子节点数字之和解题思路递归,逐层向下遍历考虑到对于此二叉树的任意节点,数字为0~9,我们有这样的递归方法:每一层将上一层传入的数字 * 10,加上当前结点数字值后传入下一层。递归出口为当前节点为叶结点,返回计数值。Java代码/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * Tr....

129. 求根到叶子节点数字之和


解题思路

递归,逐层向下遍历

考虑到对于此二叉树的任意节点,数字为0~9,我们有这样的递归方法:

每一层将上一层传入的数字 * 10,加上当前结点数字值后传入下一层。

递归出口为当前节点为叶结点,返回计数值。

 

Java代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int getNumber(TreeNode root, int num) {
        if (root == null)   return 0;
        int val = num * 10 + root.val;
        if (root.left == null && root.right == null)
            return val;
        return getNumber(root.left, val) + getNumber(root.right, val);
    }
    public int sumNumbers(TreeNode root) {
        return getNumber(root, 0);
    }
}

Leetcode 129. 求根到叶子节点数字之和

本文地址:https://blog.csdn.net/waveleting/article/details/109352432