LeetCode Lowest Common Ancestor of a Binary Search Tree

时间:2022-08-26 10:05:29

原题链接在这里:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/

题目:

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的值都小于root.val就在root.left中继续找,如果p, q的值都大于root.val就在root.right中继续找。

只有当root的val在p, q的val中间包括p, q的val时,返回root.

Time Complexity: O(h), h is height of tree. Space: O(h), 用了O(h)层stack.

AC Java:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
12         if(root == null){
13             return root;
14         }
15         if(root.val < p.val && root.val < q.val){
16             return lowestCommonAncestor(root.right,p,q);
17         }else if(root.val > p.val && root.val > q.val){
18             return lowestCommonAncestor(root.left,p,q);
19         }else{
20             return root;
21         }
22     }
23 }

进阶题目是Lowest Common Ancestor of a Binary Tree.