Interview Questions

236. Lowest Common Ancestor of a

2016-03-23  本文已影响49人  宋翰要长肉

Definition of LCA

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).

Algorithm 1

Find a path from root to given node

Complexity

Code

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        LinkedList<TreeNode> pathToP = new LinkedList<TreeNode>();
        LinkedList<TreeNode> pathToQ = new LinkedList<TreeNode>();
        if (!getPath(root, pathToP, p) || !getPath(root, pathToQ, q)) {
            return null;
        }
        Iterator<TreeNode> traverseP = pathToP.iterator();
        Iterator<TreeNode> traverseQ = pathToQ.iterator();
        TreeNode pre = null;
        while(traverseP.hasNext() && traverseQ.hasNext()) {
            TreeNode curP = traverseP.next();
            TreeNode curQ = traverseQ.next();
            if (curP == curQ) {
                pre = curP;
            } else {
                break;
            }
        }
        return pre;
    }

    private boolean getPath(TreeNode root, LinkedList<TreeNode> path, TreeNode target) {
        if (root == null) {
            return false;
        }
        path.add(root);
        if (root == target) {
            return true;
        }
        if (getPath(root.left, path, target) || getPath(root.right, path, target)) {
            return true;
        }
        path.removeLast();
        return false;
    }

Algorithm 2

Code

 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    return LCA(root, p, q);
}

private TreeNode LCA(TreeNode root, TreeNode p, TreeNode q) {
    if (root == null) {
        return null;
    }
    if (root == p || root == q) {
        return root;
    }
    TreeNode left = LCA(root.left, p, q);
    TreeNode right = LCA(root.right, p, q);
    if (left != null && right != null) {
        return root;
    }
    return (left == null)? right: left;
}
上一篇下一篇

猜你喜欢

热点阅读