Lowest Common Ancestor of a Binary Search Tree 二分搜索树的公共节点

来源:互联网 发布:php获取js变量的方法 编辑:程序博客网 时间:2024/04/28 10: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.

注意,这里是2分搜索树,保证了root.left 的节点们 < root       root.right 的节点名 > root 。

在这里介绍两种方法。

第一种:

以0,3为例。

我的方法是找个各自通过的node, 用stack存储起来

如 2 path: 6->2->0

    7 path: 6->2->4->3

2为他们的最小公共节点,易知对于2个节点,root到最小公共节点都是一样的。

先让path到一样长。(7的path pop)

path长度一样以后, 如果两个节点不一样,各自都pop

一样返回一样的节点,它就是最小公共节点。

运行时间:

代码:

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {        Stack<TreeNode> pStore =  searchNode(root, p);        Stack<TreeNode> qStore =  searchNode(root, q);        int diff = qStore.size() - pStore.size();        while (diff > 0) {            qStore.pop();            diff--;        }        while (diff < 0) {            pStore.pop();            diff++;        }        while (pStore.size() > 0){            TreeNode pTemp = pStore.pop();            TreeNode qTemp = qStore.pop();            if (pTemp == qTemp) {                return pTemp;            }        }        return null; // will not happen    }    private Stack<TreeNode> searchNode(TreeNode root, TreeNode node) {        Stack<TreeNode> path = new Stack<>();        while (root != null) {            path.add(root);            if (root.val == node.val) {                return path;            } else if (root.val > node.val) {                root = root.left;            } else {                root = root.right;            }        }        return path; //not found the root, will not happen    }

第二种方法很巧妙的

直接看代码:

    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {        if (root.val > p.val && root.val > q.val) {            return lowestCommonAncestor2(root.left, p, q);        }        else if (root.val < p.val && root.val < q.val) {            return lowestCommonAncestor2(root.right, p, q);        }        else {            return root;        }    }

运行时间:


1 0