解题思路:
方法一:递归
递归法没有中的逻辑
class Solution {public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {return recur(root, p, q);}public TreeNode recur(TreeNode root, TreeNode p, TreeNode q) {if (root == null) return null;if (root.val < p.val && root.val < q.val) {TreeNode right = recur(root.right, p, q);if (right != null) return right;}if (root.val > p.val && root.val > q.val) {TreeNode left = recur(root.left, p, q);if (left != null) return left;}return root;}
}
方法二:迭代法
可以看到二叉搜索树的题目,因为能确定好方向,所以迭代法往往更加简单
class Solution {public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {while (root != null) {if (root.val < p.val && root.val < q.val) {root = root.right;} else if (root.val > p.val && root.val > q.val) {root = root.left;} else {return root;}}return null;}
}