235. Lowest Common Ancestor of a Binary Search Tree

    xiaoxiao2021-12-10  11

    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 v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

    _______6______ / \ ___2__ ___8__ / \ / \ 0 _4 7 9 / \ 3 5

    For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

    从根节点开始遍历,找到第一个节点,它的值在p和q之间,则此节点为p与q的LCA。

    public class Solution {

        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {         TreeNode res=root;         int max=p.val>=q.val?p.val:q.val,min=p.val<q.val?p.val:q.val;         while(true){         if(res.val<=max&&res.val>=min)             return res;         else if(res.val<min){         res=res.right;         }         else{         res=res.left;         }         }     } }
    转载请注明原文地址: https://ju.6miu.com/read-700106.html

    最新回复(0)