【二叉树】二叉树根节点到叶子节点的所有路径和

2024-01-07 22:27:19

题目,来自牛客网

法1:使用全局变量

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

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

法2:不用全局变量

public class Solution {
    public int sumNumbers (TreeNode root) {
        if (root == null) {
            return 0;
        }
        return dfs(root, 0);
    }

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

文章来源:https://blog.csdn.net/Allenlzcoder/article/details/135444193
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。