Merge pull request #2115 from Projecthappy/master

新增递归法的另一种实现 0257.二叉树的所有路径
This commit is contained in:
程序员Carl
2023-06-17 08:09:13 +08:00
committed by GitHub

View File

@ -390,6 +390,8 @@ public:
```Java
//解法一
//方式一
class Solution {
/**
* 递归法
@ -428,9 +430,32 @@ class Solution {
}
}
}
//方式二
class Solution {
List<String> result = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
deal(root, "");
return result;
}
public void deal(TreeNode node, String s) {
if (node == null)
return;
if (node.left == null && node.right == null) {
result.add(new StringBuilder(s).append(node.val).toString());
return;
}
String tmp = new StringBuilder(s).append(node.val).append("->").toString();
deal(node.left, tmp);
deal(node.right, tmp);
}
}
```
```java
// 解法2
// 解法
class Solution {
/**
* 迭代法