首页 > 其他 > 详细

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

时间:2020-10-29 11:00:00      阅读:35      评论:0      收藏:0      [点我收藏+]

题目链接

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

题目分析

这个题要求我们做一个路径上的数字转化为整数,并且求和。那么路径上转化为数字的话我们可以用前序遍历即可,遇到叶子节点就往总和上面加上当前的路径数字。
求和的话有两种方式:

  1. 采用全局变量思想进行记录,辅助方法不需要返回值。
  2. 使用辅助方法返回值来计算数字和。

为什么要写第二种方法呢?因为曾经在某跳动面试过程中,写树的题目用了全局变量被面试官要求改进,当时没想出来就挂了~~

代码实现

代码一

class Solution {
    int res = 0;
    public int sumNumbers(TreeNode root) {
        helper(root, 0);
        return res;
    }

    public void helper(TreeNode root, int val){
        if(root == null){
            return;   
        }
        val = val * 10 + root.val;
        if(root.left == null && root.right == null){
            res += val;
        }
        helper(root.left, val);
        helper(root.right, val);
    }
}

代码二

class Solution {
    public int sumNumbers(TreeNode root) {
        return helper(root, 0);
    }

    public int helper(TreeNode root, int val){
        if(root == null){
            return 0;   
        }
        val = val * 10 + root.val;
        int res = 0;
        if(root.left == null && root.right == null){
            res += val;
        }
        res += helper(root.left, val);
        res += helper(root.right, val);
        return res;
    }
}

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

原文:https://www.cnblogs.com/ZJPaang/p/13894941.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!