【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;
    }
};

你可能感兴趣的:(LintCode)