求二元查找树的镜像

来源:互联网 发布:网络小贷和p2p的区别 编辑:程序博客网 时间:2024/05/20 23:08

题目:输入一颗二元查找树,将该树转换为他的镜像,即在转换后的二元查找树中左子树的节点都大于右子树的节点,如,输入二元查找树:

           11

          / \

         8   15

       /  \ / \

      6   9 12 18

   转换为:

           11

          /  \

         15   8

       /  \  / \

      18  12 9  6


递归代码:

  struct node

  {

int value;

int* left;

int* right;

  };

  void switchMirror(node* p)

  {

if(p)

{

node* temp = p->left;

p->left = p->right;

p->right = temp;

}


if(p->left)

{

switchMirror(p->left);

}

if(p->right)

{

switchMirror(p->right);

}

  }

非递归代码:

void switchMirror(node* p)

{

std::stack<node*> node_stack;

node_stack.push(p);

node* top= NULL;

node* temp = NULL;


while(node_stack.size() != 0)

{

top = node_stack.top();

node_stack.pop();

temp = top->left;

top->left= top->right;

top->right= temp;


if(top->left)

node_stack.push(top->left);

if(top->right)

node_stack.push(top->right);

}

}


0 0
原创粉丝点击