LeetCode 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最近公共祖先(Java)

题目:

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
LeetCode 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最近公共祖先(Java)_第1张图片
Note:

  • All of the nodes’ values will be unique.
  • p and q are different and both values will exist in the BST.

解答:

解法一:递归

对于二叉搜索树,最大的特点就是:左子树 如果p、q的值都小于root,则说明最近公共祖先一定在root.left
如果p、q的值都大于root,则说明最近公共祖先一定在root.right

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) {
            return root;
        }
        if(p.val<root.val && q.val<root.val) {
            return lowestCommonAncestor(root.left,p,q);
        }
        if(p.val>root.val && q.val>root.val) {
            return lowestCommonAncestor(root.right,p,q);
        }
        return root;
    }
}
解法二:迭代

同理,也可以将递归改为迭代的方式,通过变换当前节点来进行迭代

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

你可能感兴趣的:(LeetCode)