Lowest Common Ancestor of a Binary Search Tree

class Solution {
	public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
			if (root == null) return null;
			int keyVal = root.val;
			int pVal = p.val;
			int qVal = q.val;
		
	if (keyVal > pVal && keyVal > qVal) {
			return lowestCommonAncestor(root.left, p, q);
		} else if (keyVal < pVal && keyVal < qVal) {
			return lowestCommonAncestor(root.right, p, q);
		} else {
			return root;
		}
	}
}

最后更新于

这有帮助吗?