要点:
构建二叉树,
递归反转:遍历root节点,交换左右节点,然后遍历左右节点,直到节点=null。
迭代反转:使用栈stack,节点先入stack,弹出后交换左右节点,再将左右节点入栈,再弹出后进行交换,直到stack为空。
代码:
public class ReverseBinarySortTree {
public static void main(String[] args) {
// 定义节点
RBNode n1=new RBNode(5);
RBNode n2=new RBNode(4);
RBNode n3=new RBNode(6);
RBNode n4=new RBNode(1);
RBNode n5=new RBNode(2);
RBNode n6=new RBNode(9);
// 构建二叉树
n1.add(n2);
n1.add(n3);
n1.add(n4);
n1.add(n5);
n1.add(n6);
// 原始前序排序
n1.prefixOrder();
System.out.println();
System.out.println();
// 递归反转二叉树
invertRecursive(n1);
n1.prefixOrder();
System.out.println();
System.out.println();
// 迭代反转二叉树
invertIterative(n1);
n1.prefixOrder();
}
static RBNode invertRecursive(RBNode root){
if(root ==null){
return root;
}
RBNode tmp=root.left;
root.left = root.right;
root.right = tmp;
invertRecursive(root.left);
invertRecursive(root.right);
return root;
}
static RBNode invertIterative(RBNode root){
if(root==null){
return root;
}
Stack<RBNode> stack=new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
RBNode node=stack.pop();
RBNode tmp = node.left;
node.left= node.right;
node.right=tmp;
if(node.left!=null){
stack.push(node.left);
}
if(node.right!=null){
stack.push(node.right);
}
}
return root;
}
}
class RBNode {
int value;
RBNode left;
RBNode right;
public RBNode(int value) {
this.value = value;
}
public void add(RBNode node) {
if (node == null) {
return;
}
if (node.value < this.value) {
if (this.left == null) {
this.left = node;
} else {
this.left.add(node);
}
} else {
if (this.right == null) {
this.right = node;
} else {
this.right.add(node);
}
}
}
public void prefixOrder() {
System.out.println(this);
if (this.left != null) {
this.left.prefixOrder();
}
if (this.right != null) {
this.right.prefixOrder();
}
}
public void infixOrder() {
if (this.left != null) {
this.left.infixOrder();
}
System.out.println(this);
if (this.right != null) {
this.right.infixOrder();
}
}
public void postfixOrder() {
if (this.left != null) {
this.left.postfixOrder();
}
if (this.right != null) {
this.right.postfixOrder();
}
System.out.println(this);
}
@Override
public String toString() {
return "Node value=" + this.value;
}
}