题目:输入一颗二元查找树,将该树转换为它的镜像,
即在转换后的二元查找树中,左子树的结点都大于右子树的结点。
用递归和循环两种方法完成树的镜像转换。
例如输入:
8
/ \
6 10
/ \ / \
5 7 9 11
输出:
8
/ \
10 6
/ \ / \
2>循环:利用第16题,遍历一遍节点,在某个节点做处理交换左子节点和右子节点即可
即在转换后的二元查找树中,左子树的结点都大于右子树的结点。
用递归和循环两种方法完成树的镜像转换。
例如输入:
8
/ \
6 10
/ \ / \
5 7 9 11
输出:
8
/ \
10 6
/ \ / \
11 9 7 5
1>递归:前序、中序、后序遍历均可,只要在递归过程中交换左子节点和右子节点即可
public static void Digui(Node node) //前序遍历,递归交换
{
if(node == null)
return;
Node temp = node.leftChild;
node.leftChild = node.RightChild;
node.RightChild = temp;
Digui(node.leftChild);
Digui(node.RightChild);
}
2>循环:利用第16题,遍历一遍节点,在某个节点做处理交换左子节点和右子节点即可
public class Q15 {
public static void out(Node node)
{
if(node == null)
return;
out(node.leftChild);
System.out.println(node.data);
out(node.RightChild);
}
public static void Digui(Node node)
{
if(node == null)
return;
Node temp = node.leftChild;
node.leftChild = node.RightChild;
node.RightChild = temp;
Digui(node.leftChild);
Digui(node.RightChild);
}
public static void Xunhuan(Node head)
{
ArrayList<Node> list = new ArrayList<Node>();
list.add(head);
while(list.size()>0)
{
Node node = list.get(0);
Node temp = node.leftChild;
node.leftChild = node.RightChild;
node.RightChild = temp;
if(node.leftChild !=null)
list.add(node.leftChild);
if(node.RightChild != null)
list.add(node.RightChild);
list.remove(0);
}
}
public static void main(String[] args) {
Node a = new Node(8);
Node b = new Node(6);
Node c = new Node(10);
Node d = new Node(5);
Node e = new Node(7);
Node f = new Node(9);
Node g = new Node(11);
a.leftChild = b;
a.RightChild = c;
b.leftChild = d;
b.RightChild = e;
c.leftChild = f;
c.RightChild = g;
//Digui(a);
Xunhuan(a);
out(a);
}
}