第一个是普通二叉树,第二个是bst
public class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null) { return null; } if (root == p || root == q) { return root; } TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if (left != null && right != null) { return root; } if (left != null || right != null) { return left != null ? left : right; } return null; } }
public class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { int max = Math.max(p.val, q.val); int min = Math.min(p.val, q.val); if (root.val <= max && root.val >= min) { return root; } if (root.val < min) { return lowestCommonAncestor(root.right, p, q); } else { return lowestCommonAncestor(root.left, p, q); } } }
时间: 2024-10-10 18:10:27