[두 갈래 나무 BST] 235.Lowest Common Ancestor of a Binary Search Tree

1445 단어
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.
두 노드가 공통된 최소 루트를 찾으면 루트가 그 중 어느 노드일 수 있습니다.BST 성질을 분석하면 반드시 왼쪽이다
  • 좌<=root<=우면 root로 돌아갑니다
  • root<왼쪽
  • .왼쪽 <오른쪽
    class Solution {
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            if(root == null || p == null || q == null) return root;
            int left = (p.val < q.val)? p.val:q.val;
            int right = (p.val < q.val)? q.val:p.val;
                 
            if(root.val >= left && root.val <= right) return root;
            if(root.val > right) return lowestCommonAncestor(root.left, p,q);
            return lowestCommonAncestor(root.right,p,q);
        }
    }
    

    좋은 웹페이지 즐겨찾기