【LeetCode】Lowest Common Ancestor of a Binary Search Tree 解题报告

Lowest Common Ancestor of a Binary Search Tree

[LeetCode]

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/

Total Accepted: 67533 Total Submissions: 178900 Difficulty: Easy

Question

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.

Ways

首先,要知道什么是二叉搜索树!

任意节点的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
任意节点的左、右子树也分别为二叉查找树;
没有键值相等的节点。

然后题目意思应该是只会让搜索相邻的节点。比如 2,8 2,4 不会搜索2,7.

然后要利用分而治之的思想。

搜索左右子节点,如果有一个为要搜索的p或q,返回这个就好。

比如搜索2和8:

搜索左节点2,右节点8,两个分别等于要搜索的p,q,那么root(6)就是答案。

搜索 2和4:

搜索2和8,发现2是p,那么2就是答案。因为8肯定是在2的下面,两者不在统一等级,而且题目中已经是相邻的。

我感觉这个题是有点问题。

答案:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null||p==root||q==root){
            return root;
        }
        //devide
        TreeNode left=lowestCommonAncestor(root.left,p,q);
        TreeNode right=lowestCommonAncestor(root.right,p,q);

        //conquer
        if(left!=null&&right!=null){
            return root;
        }else if(left!=null){
            return left;
        }else{
            return right;
        }
    }
}

AC:11ms

Date

2016/5/1 14:05:25

你可能感兴趣的:(LeetCode)