翻转一棵二叉树。
示例:
输入:
6
/ \
4 8
/ \ / \
1 5 7 9
输出:
6
/ \
8 4
/ \ / \
9 7 5 1
package com.loo;
import java.util.ArrayList;
import java.util.List;
public class InvertTree {
static class NodeTree {
NodeTree(int v) {
value = v;
}
NodeTree left;
NodeTree right;
int value;
}
private static List<Integer> list = new ArrayList<Integer>();
/**
* @param args
*/
public static void main(String[] args) {
NodeTree root = new NodeTree(6);
NodeTree l1 = new NodeTree(4);
NodeTree l2 = new NodeTree(1);
NodeTree l3 = new NodeTree(5);
NodeTree r1 = new NodeTree(8);
NodeTree r2 = new NodeTree(7);
NodeTree r3 = new NodeTree(9);
root.left = l1;
l1.left = l2;
l1.right = l3;
root.right = r1;
r1.left = r2;
r1.right = r3;
list.clear();
inorderTraversal(root);
for(int i=0;i<list.size();i++) {
System.out.print(list.get(i));
}
System.out.println();
System.out.println("-------------------------------");
list.clear();
invertTree(root);
for(int i=0;i<list.size();i++) {
System.out.print(list.get(i));
}
System.out.println();
}
// 翻转
private static List<Integer> invertTree(NodeTree root) {
if (root!=null) {
// 左子树与右子树互换
NodeTree temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
list.add(root.value);
invertTree(root.right);
}
return list;
}
// 中序遍历树
private static List<Integer> inorderTraversal(NodeTree root) {
if (root!=null) {
invertTree(root.left);
list.add(root.value);
invertTree(root.right);
}
return list;
}
}