设为首页 加入收藏

TOP

二元查找树的翻转(镜像)的两种思路
2015-07-20 17:32:52 来源: 作者: 【 】 浏览:2
Tags:二元 查找 翻转 镜像 思路

问题描述:

输入一颗二元查找树,将该树转换为它的镜像,

即在转换后的二元查找树中,左子树的结点都大于右子树的结点。
算法:

测试用例:

10

/ \

5 11

/ \

3 7

/ \ / \

2 4 6 9

/ /

1 8

算法:

有两种思路:

①递归。对树翻转,只需对他的左右子树翻转,再交换左右子树的位置即可。

②非递归。设置一个队列queue,从根节点开始处理:人节点先入列,当队列非空时,循环进行以下处理:从队列中取出一节点,交换他的左右子树的位置,将它的左右子节点入列(若存在的话)。当队列为空时,返回。

代码实现:

①递归

template
   
    
void ReverseTree(BinaryTreeNode
    
     * t) { if (!t) return; BinaryTreeNode
     
      * temp = new BinaryTreeNode
      
       ; temp = t->LeftChild; t->LeftChild = t->RightChild; t->RightChild = temp; ReverseTree(t->LeftChild); ReverseTree(t->RightChild); return; }
      
     
    
   



非递归:

//非递归
template
   
    
void ReverseTree2(BinaryTreeNode
    
     * t) { if (!t) return; Queue
     
      *> q; q.Add(t); BinaryTreeNode
      
       * tt = new BinaryTreeNode < T >; while (!q.IsEmpty()) { q.Delete(tt); BinaryTreeNode
       
        * temp = new BinaryTreeNode < T >; temp = tt->LeftChild; tt->LeftChild = tt->RightChild; tt->RightChild = temp; if (tt->LeftChild) q.Add(tt->LeftChild); if (tt->RightChild) q.Add(tt->RightChild); } } 
       
      
     
    
   


输出测试:

InOrder(n10);
	cout << endl;
	ReverseTree(n10);
	InOrder(n10);
	cout << endl;

	ReverseTree2(n10);
	InOrder(n10);
	cout << endl;




】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇ACdream 1056 Bad Horse (种类并.. 下一篇中兴面试题:简单的背包问题的两..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Asus Armoury Crate (2025-12-26 02:52:33)
·WindowsFX (LinuxFX) (2025-12-26 02:52:30)
·[ Linux运维学习 ] (2025-12-26 02:52:27)
·HTTPS 详解一:附带 (2025-12-26 02:20:37)
·TCP/IP协议到底在讲 (2025-12-26 02:20:34)