您的位置:首页 > 其它

LeetCode 235. Lowest Common Ancestor of a Binary Search Tree(二叉搜索树的最低公共祖先)

2016-04-06 06:33 691 查看
原题网址: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.
方法一:通过递归进行遍历,时间复杂度O(n),n为节点数。

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private TreeNode lca;
private int find(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || lca != null) return 0;
int found = 0;
if (root.left != null && lca == null) found += find(root.left, p, q);
if (root.right != null && lca == null) found += find(root.right, p, q);
if (root == p) found ++;
if (root == q) found ++;
if (found == 2 && lca == null) lca = root;
return found;
}
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
find(root, p, q);
return lca;
}
}




方法二:利用BST特性,根据当前节点值大小,判断LCA是当前节点,或者在左子树、右子树中。时间复杂度O(log(n))

/**
* 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==q.val) return p;
if (p.val > q.val) {
TreeNode t = p;
p=q;
q=t;
}
if (root.val < p.val) return lowestCommonAncestor(root.right, p, q);
if (root.val == p.val) return p;
if (root.val < q.val) return root;
if (root.val == q.val) return q;
return lowestCommonAncestor(root.left, p,q);
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: