Lowest Common Ancestor of a Binary Tree III

Given two nodes of a binary tree p and q, return their lowest common ancestor (LCA).

Each node will have a reference to its parent node. The definition for Node is below:

class Node {
    public int val;
    public Node left;
    public Node right;
    public Node parent;
}

According to the definition of LCA on Wikipedia: "The lowest common ancestor of two nodes p and q in a tree T is the lowest node that has both p and q as descendants (where we allow a node to be a descendant of itself)."

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.

Constraints:

  • The number of nodes in the tree is in the range [2, 105].
  • -109 <= Node.val <= 109
  • All Node.val are unique.
  • p != q
  • p and q exist in the tree.

思路:注意node val全部是unique的,所以可以用set来收集一条路,另外一条路往上走,如果遇见node在set里面,立刻返回。T: log(h) S: log(h)

/*
// Definition for a Node.
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node parent;
};
*/

class Solution {
    public Node lowestCommonAncestor(Node p, Node q) {
        HashSet<Integer> ppath = new HashSet<>();
        Node cur = p;
        while(cur != null) {
            ppath.add(cur.val);
            cur = cur.parent;
        }
        
        cur = q;
        while(cur != null) {
            if(ppath.contains(cur.val)) {
                return cur;
            }
            cur = cur.parent;
        }
        return null;
    }
}

如果题目限制memory,那么这题就是两个linked list求交点那题;

/*
// Definition for a Node.
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node parent;
};
*/

class Solution {
    public Node lowestCommonAncestor(Node p, Node q) {
        int plen = getLength(p);
        int qlen = getLength(q);
        if(plen > qlen) {
            return findLCA(p, q, plen - qlen);
        } else {
            // plen < qlen;
            return findLCA(q, p, qlen - plen);
        }
    }
    
    // make assumption plen > qlen;
    private Node findLCA(Node p, Node q, int step) {
        while(step > 0) {
            p = p.parent;
            step--;
        }
        while(p != q) {
            p = p.parent;
            q = q.parent;
        }
        return p;
    }
    
    private int getLength(Node node) {
        int len = 0;
        while(node != null) {
            node = node.parent;
            len++;
        }
        return len;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值