二叉树左右子树交换(C++)

递归:
void exchange(BTree *rt){
 BTree *temp = NULL;
 if(rt->lchild == NULL && rt->rchild == NULL)
        return;
 else{
       temp = rt->lchild;
       rt->lchild = rt->rchild;
       rt->rchild = temp;
 }
 if(rt->lchild)
      exchange(rt->lchild);
 if(rt->rchild)
      exchange(rt->rchild);
}

非递归:
Stack是一个定义好的通用堆栈类型,支持初始化/进站/出战等操作
int Exchange(BiTree *T)
{
  Stack s;
  BiTree *p;
  InitStack(s);
  p=T;
  while(p||!StackEmpty(s)){
    if(p){
      push(s,p);
      p->Lchild;
    }
    else{
      pop(s,p);
      t=p->Rchild;
      p->Rchild=p->Lchild;
      p->Lchild=t;
      p-=->Lchild;
    }
  }
return 1;
}

转载于:https://www.cnblogs.com/zhang-qiang/archive/2011/04/21/2024317.html

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是完善后的代码: ```c++ #include "binary_tree.h" #include <stack> using namespace std; void swapTree(TreeNode* root) { if (!root) return; stack<TreeNode*> s; s.push(root); while (!s.empty()) { TreeNode* node = s.top(); s.pop(); swap(node->left, node->right); if (node->left) s.push(node->left); if (node->right) s.push(node->right); } } void postOrder(TreeNode* root) { if (!root) return; stack<TreeNode*> s; TreeNode* last_visited = nullptr; while (root || !s.empty()) { if (root) { s.push(root); root = root->left; } else { TreeNode* node = s.top(); if (node->right && last_visited != node->right) { root = node->right; } else { cout << node->val << " "; last_visited = node; s.pop(); } } } } int main() { TreeNode* root = createBinaryTree(); cout << "Original tree: "; postOrder(root); cout << endl; swapTree(root); cout << "Swapped tree: "; postOrder(root); cout << endl; return 0; } ``` 其中,`swapTree`函数使用非递归的方式实现了二叉树左右子树交换。具体来说,我们使用一个栈来存储待处理的节点,从栈中取出一个节点后,交换它的左右子树,并将左右子树分别入栈,以便后续处理。 `postOrder`函数实现了二叉树的后序遍历。我们使用栈来模拟递归,具体来说,我们将根节点和它的左子树依次入栈,直到没有左子树可入栈为止。然后,我们不断从栈中取出节点,并检查它的右子树是否已经被访问过。如果没有,就将右子树和它的左子树依次入栈;如果已经被访问过,就输出该节点的值。为了避免重复访问右子树,我们使用`last_visited`变量来保存上一个访问的节点。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值