leetcode 235: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.

題目大意:找出兩個節點的最低公共祖先(注意:一個節點可以看做自己的後代節點)

解題思路:

給出當前遍歷到的結點r,找出結點p,q的最低公共祖先。
1.如果兩個結點分別位於r節點兩側,則根節點爲最小公共祖先;
如果r節點小於p節點的值,則在r結點的左子樹中繼續尋找;否則在r結點的右子樹中尋找;

代碼實現:

/**
 * 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((p.val - root.val ) * (q.val - root.val) <=0)
            return root;
        else if(p.val > root.val)
            return  lowestCommonAncestor(root.right,p,q);
        else
            return lowestCommonAncestor(root.left,p,q);
    }
}
發佈了61 篇原創文章 · 獲贊 14 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章