leetcode235:Lowest Common Ancestor of a Binary Search Tree

来源:互联网 发布:mac os x lion是什么 编辑:程序博客网 时间:2024/05/17 22:01

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,用数据结构ArrayList记录其自底向上的路径节点。对于节点q,自底向上查找其祖先节点是否在ArrayList中

public  TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {        HashMap<TreeNode,TreeNode> hs = new HashMap<TreeNode,TreeNode>();        if(root==null || p==root || q == root )        return root;        hs.put(root, root);        Queue<TreeNode> queue = new LinkedList<TreeNode>(); //LinkedList是Queue接口的一个实现类        queue.add(root);        while(!queue.isEmpty() ){        TreeNode tmp = queue.peek();        if(tmp.left !=null){        queue.add(tmp.left);        hs.put(tmp.left, tmp);        }        if(tmp.right !=null){        queue.add(tmp.right);        hs.put(tmp.right, tmp);        }        queue.poll();        }        ArrayList<TreeNode> list = new ArrayList<TreeNode>();        TreeNode tmp = p;        while(tmp!=root){        list.add(tmp);        tmp = hs.get(tmp);        }        tmp = q;        while(tmp!=root){        if(list.contains(tmp))        return tmp;        tmp = hs.get(tmp);        }        return root;    }
解法二:仅仅适用于排序二叉树
public  TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {if(root == null)return root;if(p.val<root.val && q.val<root.val){return lowestCommonAncestor(root.left,p,q);}else if(p.val>root.val && q.val>root.val){return lowestCommonAncestor(root.right,p,q);}else return root;}


                                             
0 0
原创粉丝点击