mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
feat(0257): 新增两种java解法
This commit is contained in:
@ -283,6 +283,7 @@ public:
|
||||
Java:
|
||||
|
||||
```Java
|
||||
//解法一
|
||||
class Solution {
|
||||
/**
|
||||
* 递归法
|
||||
@ -321,6 +322,52 @@ class Solution {
|
||||
}
|
||||
}
|
||||
|
||||
//解法二(常规前序遍历,不用回溯),更容易理解
|
||||
class Solution {
|
||||
public List<String> binaryTreePaths(TreeNode root) {
|
||||
List<String> res = new ArrayList<>();
|
||||
helper(root, new StringBuilder(), res);
|
||||
return res;
|
||||
}
|
||||
|
||||
public void helper(TreeNode root, StringBuilder sb, List<String> res) {
|
||||
if (root == null) {return;}
|
||||
// 遇到叶子结点就放入当前路径到res集合中
|
||||
if (root.left == null && root.right ==null) {
|
||||
sb.append(root.val);
|
||||
res.add(sb.toString());
|
||||
// 记得结束当前方法
|
||||
return;
|
||||
}
|
||||
helper(root.left,new StringBuilder(sb).append(root.val + "->"),res);
|
||||
helper(root.right,new StringBuilder(sb).append(root.val + "->"),res);
|
||||
}
|
||||
}
|
||||
|
||||
//针对解法二优化,思路本质是一样的
|
||||
class Solution {
|
||||
public List<String> binaryTreePaths(TreeNode root) {
|
||||
List<String> res = new ArrayList<>();
|
||||
helper(root, "", res);
|
||||
return res;
|
||||
}
|
||||
|
||||
public void helper(TreeNode root, String path, List<String> res) {
|
||||
if (root == null) {return;}
|
||||
// 由原始解法二可以知道,root的值肯定会下面某一个条件加入到path中,那么干脆直接在这一步加入即可
|
||||
StringBuilder sb = new StringBuilder(path);
|
||||
sb.append(root.val);
|
||||
if (root.left == null && root.right ==null) {
|
||||
res.add(sb.toString());
|
||||
}else{
|
||||
// 如果是非叶子结点则还需要跟上一个 “->”
|
||||
sb.append("->");
|
||||
helper(root.left,sb.toString(),res);
|
||||
helper(root.right,sb.toString(),res);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Python:
|
||||
@ -350,7 +397,7 @@ class Solution:
|
||||
|
||||
```
|
||||
Go:
|
||||
|
||||
|
||||
```go
|
||||
func binaryTreePaths(root *TreeNode) []string {
|
||||
res := make([]string, 0)
|
||||
|
Reference in New Issue
Block a user