您的位置:首页 > 其它

二叉树的反转,递归实现和非递归实现。

2016-03-05 19:38 330 查看
package com.alg;

import java.util.Stack;

/**
* Created by lchli on 2016/3/5.
*/
public class BTreeRevert {

public static class Node {
public Node left;
public Node right;
public Object data;
}

/**
* 递归实现。
*
* @param root
*/
public static void recusiveRevert(Node root) {
if (root == null) {
return;
}
swap(root);
recusiveRevert(root.left);
recusiveRevert(root.right);

}

/**
* 非递归实现。
*
* @param root
*/
public static void stackRevert(Node root) {
if (root == null) {
return;
}
Stack<Node> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
Node current = stack.pop();
swap(current);
if (current.left != null) {
stack.push(current.left);
}
if (current.right != null) {
stack.push(current.right);
}
}

}

private static void swap(Node root) {
Node tmp = root.left;
root.left = root.right;
root.right = tmp;
}

/**
* test.前序输出。
*
* @param root
*/
public static void preorderOutput(Node root) {
if (root == null) {
return;
}
System.out.print(root.data);
preorderOutput(root.left);
preorderOutput(root.right);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉树反转