86.png

    1. /*
    2. 试编写一个算法将一颗二叉树的所有节点的左右子树进行交换。
    3. 分析:
    4. 我们仍然可以采用递归的方式进行交换
    5. */
    6. struct biTree {
    7. char data;
    8. struct biTree *lchild;
    9. struct biTree *rchild;
    10. };
    11. #include <stdio.h>
    12. #include <stdlib.h>
    13. void swapTree(biTree *T) {//其本质就是从叶子节点开始进行交换,一路推进到根节点
    14. struct biTree *p = T,*t;
    15. if (!p) return;
    16. if (!p->lchild&&!p->rchild) {//如果没有左右孩子,就不需要交换了,直接返回
    17. return;
    18. }
    19. else {
    20. swapTree(p->lchild);//交换左子树
    21. t = p->lchild;
    22. p->lchild = p->rchild;
    23. p->rchild = t;
    24. swapTree(p->rchild);//交换右子树
    25. }
    26. }
    27. int main() {
    28. int num;
    29. struct biTree *T = (struct biTree*)malloc(sizeof(struct biTree));
    30. biTree *create(biTree *);
    31. void inOrder(biTree *);
    32. T = create(T);//创建一颗二叉树
    33. inOrder(T);
    34. printf("\n");
    35. swapTree(T);
    36. inOrder(T);
    37. return 0;
    38. }