【LintCode】474.最近公共祖先 II

描述

给一棵二叉树和二叉树中的两个节点,找到这两个节点的最近公共祖先LCA。

两个节点的最近公共祖先,是指两个节点的所有父亲节点中(包括这两个节点),离这两个节点最近的公共的节点。

每个节点除了左右儿子指针以外,还包含一个父亲指针parent,指向自己的父亲。

样例
样例 1:

输入:{4,3,7,#,#,5,6},3,5
输出:4
解释:
     4
     / \
    3   7
       / \
      5   6
LCA(3, 5) = 4
样例 2:

输入:{4,3,7,#,#,5,6},5,6
输出:7
解释:
      4
     / \
    3   7
       / \
      5   6
LCA(5, 6) = 7

解法

/**
 * 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) {
        // write your code here
        if(root == NULL)
            return NULL;
        if(root == A || root == B)
            return root;
        ParentTreeNode* left = lowestCommonAncestorII(root->left,A,B);
        ParentTreeNode* right = lowestCommonAncestorII(root->right,A,B);
        
        if(left && right)
            return root;
        return left ? left:right;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值