235. Lowest Common Ancestor of a Binary Search Tree

来源:互联网 发布:mac上pdf软件 编辑:程序博客网 时间:2024/06/06 02:53

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,无重复BST的性质:左子树元素<根元素<右子树元素 、 中序遍历是有序的。

这里可以找给定的两个节点,找节点就是BST的普通查找过程,小于去左子树找,大于取右子树找,等于就找到了。

查找的过程中可以记录到路径,查找P的时候把路径记录下来塞入hashmap,再查找Q,查找Q的过程中同样有路径,记录最后一次出现过的路径节点就是所求。

 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q){if(root==null)return root;if(p==q)return q;HashMap<TreeNode, Integer> hashmap=new HashMap<>();hashmap.put(root, 0);TreeNode tn=root;TreeNode common=null;while(tn!=null){int cmp=p.val-tn.val;hashmap.put(tn, hashmap.size());if(cmp==0||tn==p)break;else if(cmp>0)tn=tn.right;else{tn=tn.left;}}tn=root;while(tn!=null){int cmp=q.val-tn.val;if(hashmap.containsKey(tn))common=tn;if(cmp==0||tn==q)break;else if(cmp>0)tn=tn.right;else {tn=tn.left;}}return common;}


----------------------------------------------------------------------------------------------------

https://discuss.leetcode.com/topic/18387/3-lines-with-o-1-space-1-liners-alternatives


Just walk down from the whole tree's root as long as both p and q are in the same subtree (meaning their values are both smaller or both larger than root's). This walks straight from the root to the LCA, not looking at the rest of the tree, so it's pretty much as fast as it gets. A few ways to do it:


当前检查到的节点值分别和p、q作差,得到的差值相乘,由于这是BST,同号说明在当前检查节点的同一边。


public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {    while ((root.val - p.val) * (root.val - q.val) > 0)        root = p.val < root.val ? root.left : root.right;    return root;}

0 0