Skip to content

Commit e950990

Browse files
Merge pull request #199 from nmydt/patch-2
添加 二叉树中递归带着回溯 Java代码
2 parents 19b6ea1 + af6340c commit e950990

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

problems/二叉树中递归带着回溯.md

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,85 @@ if (cur->right) {
175175

176176

177177
Java:
178+
100. 相同的树:递归代码
179+
```java
180+
class Solution {
181+
public boolean compare(TreeNode tree1, TreeNode tree2) {
182+
183+
if(tree1==null && tree2==null)return true;
184+
if(tree1==null || tree2==null)return false;
185+
if(tree1.val!=tree2.val)return false;
186+
// 此时就是:左右节点都不为空,且数值相同的情况
187+
// 此时才做递归,做下一层的判断
188+
boolean compareLeft = compare(tree1.left, tree2.left); // 左子树:左、 右子树:左
189+
boolean compareRight = compare(tree1.right, tree2.right); // 左子树:右、 右子树:右
190+
boolean isSame = compareLeft && compareRight; // 左子树:中、 右子树:中(逻辑处理)
191+
return isSame;
192+
193+
}
194+
boolean isSameTree(TreeNode p, TreeNode q) {
195+
return compare(p, q);
196+
}
197+
}
198+
```
199+
257. 二叉树的所有路径: 回溯代码
200+
```java
201+
class Solution {
202+
public void traversal(TreeNode cur, List<Integer> path, List<String> result) {
203+
path.add(cur.val);
204+
// 这才到了叶子节点
205+
if (cur.left == null && cur.right == null) {
206+
String sPath="";
207+
for (int i = 0; i < path.size() - 1; i++) {
208+
sPath += ""+path.get(i);
209+
sPath += "->";
210+
}
211+
sPath += path.get(path.size() - 1);
212+
result.add(sPath);
213+
return;
214+
}
215+
if (cur.left!=null) {
216+
traversal(cur.left, path, result);
217+
path.remove(path.size()-1); // 回溯
218+
}
219+
if (cur.right!=null) {
220+
traversal(cur.right, path, result);
221+
path.remove(path.size()-1); // 回溯
222+
}
223+
}
224+
225+
public List<String> binaryTreePaths(TreeNode root) {
226+
List<String> result = new LinkedList<>();
227+
List<Integer> path = new LinkedList<>();
228+
if (root == null) return result;
229+
traversal(root, path, result);
230+
return result;
231+
}
232+
}
233+
234+
```
235+
如下为精简之后的递归代码:(257. 二叉树的所有路径)
236+
```java
237+
class Solution {
238+
public void traversal(TreeNode cur, String path, List<String> result) {
239+
path += cur.val; //
240+
if (cur.left == null && cur.right == null) {
241+
result.add(path);
242+
return;
243+
}
244+
if (cur.left!=null) traversal(cur.left, path + "->", result); // 左 回溯就隐藏在这里
245+
if (cur.right!=null) traversal(cur.right, path + "->", result); // 右 回溯就隐藏在这里
246+
}
178247

248+
public List<String> binaryTreePaths(TreeNode root) {
249+
List<String> result = new LinkedList<>();
250+
String path = "";
251+
if (root == null) return result;
252+
traversal(root, path, result);
253+
return result;
254+
}
255+
}
256+
```
179257

180258
Python:
181259

0 commit comments

Comments
 (0)