Skip to content

Commit 3a77a3c

Browse files
authored
Update LastSameInTree.java
1 parent 9ca9ece commit 3a77a3c

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

code/offer/src/Chap7/LastSameInTree.java

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,23 +18,28 @@ public Node findLastSame(Node root, Node a, Node b) {
1818

1919
LinkedList<Node> path1 = new LinkedList<>();
2020
LinkedList<Node> path2 = new LinkedList<>();
21-
collectNode(root, a, path1);
22-
collectNode(root, b, path2);
21+
22+
LinkedList<Node> res1 = new LinkedList<>();
23+
LinkedList<Node> res2 = new LinkedList<>();
24+
collectNode(root, a, path1, res1);
25+
collectNode(root, b, path2, res2);
2326
return getLastSameNode(path1, path2);
2427
}
2528

2629
/**
2730
* 收集含有结点node的路径上的所有结点,形成一条链表
2831
*/
29-
private boolean collectNode(Node root, Node node, LinkedList<Node> path) {
30-
if (root == node) return true;
32+
private void collectNode(Node root, Node node, LinkedList<Node> path, LinkedList<Node> res) {
33+
if (root == null || node == null) return;
3134
path.add(root);
35+
if (root = node) {
36+
res.addAll(path);
37+
}
3238
for (Node child : root.children) {
33-
if (collectNode(child, node, path)) return true;
39+
if (collectNode(child, node, path));
3440
}
3541
// 该条路径上没找到结点node就要从路径中移除
36-
path.removeLast();
37-
return false;
42+
path.remove(path.size() - 1);
3843
}
3944

4045
/**
@@ -51,4 +56,4 @@ private Node getLastSameNode(LinkedList<Node> path1, LinkedList<Node> path2) {
5156
}
5257
return lastSameNode;
5358
}
54-
}
59+
}

0 commit comments

Comments
 (0)