《LeetCode力扣练习》代码随想录——二叉树(二叉搜索树的最近公共祖先—Java)
刷题思路来源于 代码随想录
235. 二叉搜索树的最近公共祖先
-
迭代法
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ 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.left; } else if (root.val < p.val && root.val < q.val) { root = root.right; } else { return root; } } return root; } }