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

题目链接

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;
    }
}
原文地址:https://www.cnblogs.com/ZJPaang/p/13894941.html