From 41f2652d8677bbe97cd1fe7792415228f1032bb7 Mon Sep 17 00:00:00 2001 From: bourne-3 <595962708@qq.com> Date: Tue, 7 Sep 2021 12:13:27 +0800 Subject: [PATCH] =?UTF-8?q?=C2=96129=E6=B1=82=E6=A0=B9=E8=8A=82=E7=82=B9?= =?UTF-8?q?=E7=9A=84=E5=8F=B6=E8=8A=82=E7=82=B9=E6=95=B0=E5=AD=97=E4=B9=8B?= =?UTF-8?q?=E5=92=8CJava=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0129.求根到叶子节点数字之和.md | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/problems/0129.求根到叶子节点数字之和.md b/problems/0129.求根到叶子节点数字之和.md index 3439cd25..a330991e 100644 --- a/problems/0129.求根到叶子节点数字之和.md +++ b/problems/0129.求根到叶子节点数字之和.md @@ -164,6 +164,54 @@ public: Java: +```java +class Solution { + List path = new ArrayList<>(); + int res = 0; + + public int sumNumbers(TreeNode root) { + // 如果节点为0,那么就返回0 + if (root == null) return 0; + // 首先将根节点放到集合中 + path.add(root.val); + // 开始递归 + recur(root); + return res; + } + + public void recur(TreeNode root){ + if (root.left == null && root.right == null) { + // 当是叶子节点的时候,开始处理 + res += listToInt(path); + return; + } + + if (root.left != null){ + // 注意有回溯 + path.add(root.left.val); + recur(root.left); + path.remove(path.size() - 1); + } + if (root.right != null){ + // 注意有回溯 + path.add(root.right.val); + recur(root.right); + path.remove(path.size() - 1); + } + return; + } + + public int listToInt(List path){ + int sum = 0; + for (Integer num:path){ + // sum * 10 表示进位 + sum = sum * 10 + num; + } + return sum; + } +} +``` + Python: ```python3 class Solution: