当前位置:   article > 正文

编写算法交换二叉树中所有节点的左右子树_二叉树交换所有左右子树算法

二叉树交换所有左右子树算法

实现代码如下:

非递归算法:

  1. //root是根节点
  2. void swap(){
  3. BiNode * queue[100], * temp, * root1;
  4. int first = 0, last = 0;
  5. queue[first++] = root;
  6. while(first != last){
  7. root1 = queue[++last];
  8. temp = root1->lchild;
  9. root1->lchild = root1->rchild;
  10. root1->rchild = temp;
  11. if(root1->lchild != NULL)
  12. queue[first++] = root1->lchild;
  13. if(root1->rchild != NULL)
  14. queue[first++] = root1->rchild;
  15. }
  16. }


递归算法:

  1. root是根节点
  2. BiNode * temp, * root1;
  3. void swap(BiNode root1){
  4. if(root1 == NULL) return;
  5. else{
  6. temp = root1->lchild;
  7. root1->lchild = root1->rchild;
  8. root1->rchild = temp;
  9. swap(root1->lchild);
  10. swap(root1->rchild);
  11. }
  12. }


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/737682
推荐阅读
相关标签
  

闽ICP备14008679号