1. 题目
2. 思路
(1) DFS
3. 代码
import java.util.Deque;
import java.util.LinkedList;
public class Test {
public static void main(String[] args) {
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
class Solution {
private Deque<TreeNode> stack;
private TreeNode p;
private TreeNode q;
private TreeNode pre;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
stack = new LinkedList<>();
this.p = p;
this.q = q;
query(root);
while (!stack.isEmpty()) {
root = stack.peek();
if (exist(root)) {
break;
}
pre = stack.pop();
}
return root;
}
private void query(TreeNode root) {
if (stack.peek() == p || root == null) {
return;
}
stack.push(root);
query(root.left);
query(root.right);
if (stack.peek() == p) {
return;
}
stack.pop();
}
private boolean exist(TreeNode root) {
if (root == null || root == pre) {
return false;
}
if (root == q) {
return true;
}
return exist(root.left) || exist(root.right);
}
}
|