# 二叉树结点位置对调的问题

typedef struct node_t {

``````struct node_t* parent;
struct node_t* left;
struct node_t* right;

int data;``````

} node;

`````` 1                    1
/ \                  / \``````

/ / \
2 3 8 3
/ / / /
4 5 6 ----> 4 5 6
/ / \
9 8 9 2
/ /
0 0

// two和eight是内定的, 不要在意这些细节
printf("%d %d %dn", two->data,

``````    eight->data,
eight->right); // 2 8 0``````

swap(two, eight);
printf("%d %d %dn", two->data,

``````    eight->data,
eight->right->data); // 2 8 5``````

a123456678 2016-06-07 16:39:20 2150 0
1 条回答

• ``````void swap(node* a, node* b)
{
// 处理a与b相邻的情况，
// 基本思路：将a指向b的邻边指向自己，将b指向a的邻边指向自己，交换的时候就不会出错
if (a->left == b){
a->left = a;
b->parent = b;
}
else if (a->right == b){
a->right = a;
b->parent = b;
}
else if (a->parent == b) {
a->parent = a;
if (b->left == a)
b->left == b
else
b->right == b;
}

node* tmp = b->parent;
b->parent = a->parent;
a->parent = tmp;
tmp = b->right;
b->right = a->right;
a->right = tmp;
tmp = b->left;
b->left = a->left;
a->left = tmp;
}``````
2019-07-17 19:30:28
赞同 展开评论 打赏

921
1
0
287
1
0
3074
1
0
9640
2
0
1979
1
0
2201
2
0
2097
2
0
5039
2
0
2502
2
0
2456
1
0