Skip to content

Commit

Permalink
Update 二叉树中递归带着回溯.md
Browse files Browse the repository at this point in the history
添加 二叉树:以为使用了递归,其实还隐藏着回溯 Java代码
  • Loading branch information
nmydt authored May 19, 2021
1 parent 786137d commit af6340c
Showing 1 changed file with 78 additions and 0 deletions.
78 changes: 78 additions & 0 deletions problems/二叉树中递归带着回溯.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,85 @@ if (cur->right) {


Java:
100. 相同的树:递归代码
```java
class Solution {
public boolean compare(TreeNode tree1, TreeNode tree2) {

if(tree1==null && tree2==null)return true;
if(tree1==null || tree2==null)return false;
if(tree1.val!=tree2.val)return false;
// 此时就是:左右节点都不为空,且数值相同的情况
// 此时才做递归,做下一层的判断
boolean compareLeft = compare(tree1.left, tree2.left); // 左子树:左、 右子树:左
boolean compareRight = compare(tree1.right, tree2.right); // 左子树:右、 右子树:右
boolean isSame = compareLeft && compareRight; // 左子树:中、 右子树:中(逻辑处理)
return isSame;

}
boolean isSameTree(TreeNode p, TreeNode q) {
return compare(p, q);
}
}
```
257. 二叉树的所有路径: 回溯代码
```java
class Solution {
public void traversal(TreeNode cur, List<Integer> path, List<String> result) {
path.add(cur.val);
// 这才到了叶子节点
if (cur.left == null && cur.right == null) {
String sPath="";
for (int i = 0; i < path.size() - 1; i++) {
sPath += ""+path.get(i);
sPath += "->";
}
sPath += path.get(path.size() - 1);
result.add(sPath);
return;
}
if (cur.left!=null) {
traversal(cur.left, path, result);
path.remove(path.size()-1); // 回溯
}
if (cur.right!=null) {
traversal(cur.right, path, result);
path.remove(path.size()-1); // 回溯
}
}

public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new LinkedList<>();
List<Integer> path = new LinkedList<>();
if (root == null) return result;
traversal(root, path, result);
return result;
}
}

```
如下为精简之后的递归代码:(257. 二叉树的所有路径)
```java
class Solution {
public void traversal(TreeNode cur, String path, List<String> result) {
path += cur.val; //
if (cur.left == null && cur.right == null) {
result.add(path);
return;
}
if (cur.left!=null) traversal(cur.left, path + "->", result); // 左 回溯就隐藏在这里
if (cur.right!=null) traversal(cur.right, path + "->", result); // 右 回溯就隐藏在这里
}

public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new LinkedList<>();
String path = "";
if (root == null) return result;
traversal(root, path, result);
return result;
}
}
```

Python:

Expand Down

0 comments on commit af6340c

Please sign in to comment.