我已经为函数编写了一个解决方案,
char
. 是
FindMirrorNode(r, n) == FindMirrorNodeData(r, n->data)
?
在将镜像节点保持在堆栈上的同时,必须遍历整个树来搜索给定的数据。这是一个非常简单的解决方案,仍然非常有效。
如果需要,可以将尾调用转换为
while
.
static Node* FindMirrorNodeRec(char given, Node* left, Node* right)
{
// if either node is NULL then there is no mirror node
if (left == NULL || right == NULL)
return NULL;
// check the current candidates
if (given == left->data)
return right;
if (given == right->data)
return left;
// try recursively
// (first external then internal nodes)
Node* res = FindMirrorNodeRec(given, left->left, right->right);
if (res != NULL)
return res;
return FindMirrorNodeRec(given, left->right, right->left);
}
Node* FindMirrorNodeData(Node* root, char given)
{
if (root == NULL)
return NULL;
if (given == root->data)
return root;
// call the search function
return FindMirrorNodeRec(given, root->left, root->right);
}