描述
給一棵二叉樹和二叉樹中的兩個節點,找到這兩個節點的最近公共祖先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;
}
};