百度云太TNND扯淡了# Hardware - 计算机硬件
e*s
1 楼
题目是find lowest common ancestor in a binary tree (不是BST)。请问
(1)是不是一个node不能是本身的ancestor? 比如如果p是q的parent, 则lowest common
ancestor是p的parent (而不是p)?
(2)以下的code是career cup 上找到的,是不是没有考虑初始的时候 root == p ||
root ==q的情况?
请大牛讲讲,能给个标准的code就更感谢了!
Node *LowestCommonAncestor(Node *root, Node* p, Node * q) {
if(root == NULL)
return NULL;
if (p == NULL || q == NULL)
return NULL;
if(root->leftChild == p || root->leftChild == q || root->rightChild == p||
root->rightChild == q)
return root;
Node * L = LowestCommonAncestor(root->leftChild, p, q);
Node * R = LowestCommonAncestor(root->rightChild, p, q);
if(L != NULL && R != NULL)
return root;
else if (L != NULL)
return L;
else
return R;
}
(1)是不是一个node不能是本身的ancestor? 比如如果p是q的parent, 则lowest common
ancestor是p的parent (而不是p)?
(2)以下的code是career cup 上找到的,是不是没有考虑初始的时候 root == p ||
root ==q的情况?
请大牛讲讲,能给个标准的code就更感谢了!
Node *LowestCommonAncestor(Node *root, Node* p, Node * q) {
if(root == NULL)
return NULL;
if (p == NULL || q == NULL)
return NULL;
if(root->leftChild == p || root->leftChild == q || root->rightChild == p||
root->rightChild == q)
return root;
Node * L = LowestCommonAncestor(root->leftChild, p, q);
Node * R = LowestCommonAncestor(root->rightChild, p, q);
if(L != NULL && R != NULL)
return root;
else if (L != NULL)
return L;
else
return R;
}