本文介绍了二叉树的镜像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设有一棵树:
1
/
2 3
/
4 5
那么镜像将是:
1
/
3 2
/
5 4
假设节点是这样的结构:
Assume the nodes are of this structure:
struct node{
node left;
node right;
int value;
}
有人可以为此提出一个算法吗?
Can someone suggest an algorithm for this?
推荐答案
听起来像家庭作业.
看起来很简单.编写一个递归例程,深度优先访问每个节点,并构建左右颠倒的镜像树.
It looks very easy. Write a recursive routine that depth-first visits every node and builds the mirror tree with left and right reversed.
struct node *mirror(struct node *here) {
if (here == NULL)
return NULL;
else {
struct node *newNode = malloc (sizeof(struct node));
newNode->value = here->value;
newNode->left = mirror(here->right);
newNode->right = mirror(here->left);
return newNode;
}
}
这会返回一棵新树 - 其他一些答案会在适当的位置执行此操作.取决于你的作业要求你做什么:)
This returns a new tree - some other answers do this in place. Depends on what your assignment asked you to do :)
这篇关于二叉树的镜像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!