Find first intersection between two paths


  • 0
    L

    First find the paths from the root to the two nodes, and find the intersection between the two lists.

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        LinkedList<TreeNode> pl = new LinkedList<TreeNode>();
        LinkedList<TreeNode> ql = new LinkedList<TreeNode>();
        findPath(root, p, pl);
        findPath(root, q, ql);
        //find first intersection node
        LinkedList<TreeNode> longPath = pl.size() > ql.size() ? pl : ql;
        int diff = Math.abs(pl.size() - ql.size());
        for (int i = 0; i < diff; i++) {
            longPath.removeFirst();
        }
        while (pl.peek() != ql.peek()) {
            pl.removeFirst();
            ql.removeFirst();
        }
        return pl.peek();
    }
    
    public boolean findPath(TreeNode root, TreeNode n, LinkedList<TreeNode> list) {
        if (root == null) {
            return false;
        }
        
        if (root == n || findPath(root.left, n, list) || findPath(root.right, n, list)) {
            list.addLast(root);
            return true;
        }
        return false;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.