使用深度优先
/**
* @author xnl
* @Description:
* @date: 2022/6/16 23:16
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
}
private TreeNode ans;
public Solution(){
ans = null;
}
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
this.dfs(root, p.val, q.val);
return ans;
}
/**
* 使用深度优先遍历,也就是使用递归
* 定义左右两个Boolean值,代表是否找到左右子树匹配的节点
* @param root
* @param p
* @param q
* @return
*/
private boolean dfs(TreeNode root, int p, int q){
if (root == null){
return false;
}
boolean lson = dfs(root.left, p , q);
boolean rson = dfs(root.right, p, q);
if ((lson && rson) || ((root.val == p || root.val == q) && (lson || rson))){
ans = root;
}
return lson || rson || (root.val == p || root.val == q);
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}