474. Lowest Common Ancestor II

  1. Lowest Common Ancestor II
    中文English
    Given the root and two nodes in a Binary Tree. Find the lowest common ancestor(LCA) of the two nodes.

The lowest common ancestor is the node with largest depth which is the ancestor of both nodes.

The node has an extra attribute parent which point to the father of itself. The root’s parent is null.

Example
Example 1:

Input:
4
/
3 7
/
5 6
and 3,5
Output: 4
Explanation:LCA(3, 5) = 4

Example 2:

Input:
4
/
3 7
/
5 6
and 5,6
Output: 7
Explanation:LCA(5, 6) = 7

解法1:
A先往上拱,直到root,所有节点放入set。然后B再往上拱,看访问的节点是否在set中。
代码如下:

/**
 * Definition of ParentTreeNode:
 * class ParentTreeNode {
 * public:
 *     int val;
 *     ParentTreeNode *parent, *left, *right;
 * }
 */


class Solution {
public:
    /*
     * @param root: The root of the tree
     * @param A: node in the tree
     * @param B: node in the tree
     * @return: The lowest common ancestor of A and B
     */
    ParentTreeNode * lowestCommonAncestorII(ParentTreeNode * root, ParentTreeNode * A, ParentTreeNode * B) {
        if (!root) return NULL;
        if (root == A || root == B) return root;
        
        unordered_set<ParentTreeNode *> s;
        ParentTreeNode * tempA = A;
        ParentTreeNode * tempB = B;
        
        while(tempA) {
            s.insert(tempA);
            tempA = tempA->parent;
        }
        
        while (tempB) {
            if (s.find(tempB) == s.end()) {
                tempB = tempB->parent;
            } else {
                return tempB;
            }
        }
        
       // return root;
    }
};

解法2:A和B一起往上拱,所经过的节点都放入set。不管谁先遇到set中的元素就返回。

class Solution {
public:
    /*
     * @param root: The root of the tree
     * @param A: node in the tree
     * @param B: node in the tree
     * @return: The lowest common ancestor of A and B
     */
    ParentTreeNode * lowestCommonAncestorII(ParentTreeNode * root, ParentTreeNode * A, ParentTreeNode * B) {
        if (!root) return NULL;
        if (root == A || root == B) return root;
        
        unordered_set<ParentTreeNode *> s;
        ParentTreeNode * tempA = A;
        ParentTreeNode * tempB = B;
        
        while(tempA || tempB) {
            if (tempA && s.find(tempA) != s.end()) return tempA;
            s.insert(tempA);
            if (tempB && s.find(tempB) != s.end()) return tempB;
            s.insert(tempB);
            
            tempA = tempA->parent;
            tempB = tempB->parent;
        }
        
       // return root;
    }
};

解法3:用Lowest Common Ancestor的分治法,不过没有用到parent,效率低。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值