Java实现二叉树的遍历
public class BinaryTreeNode {
int value;
BinaryTreeNode left;
BinaryTreeNode right;
// 前序遍历
public static void preOrder(BinaryTreeNode tree) {
if (tree == null)
return;
System.out.print(tree.value + " ");
preOrder(tree.left);
preOrder(tree.right);
}
/**
* 二叉树前序遍历的循环实现方式
*
* @param tree
*/
public static void preOrderLoop(BinaryTreeNode tree) {
if (tree == null)
return;
Stack<BinaryTreeNode> stack = new Stack<BinaryTreeNode>();
BinaryTreeNode node = tree;
while (node != null || !stack.isEmpty()) {
if (node != null) {
stack.push(node);
System.out.print(node.value + " ");
node = node.left;
} else {
BinaryTreeNode item = stack.pop();
node = item.right;
}
}
}
// 中序遍历
public static void inOrder(BinaryTreeNode tree) {
if (tree == null)
return;
inOrder(tree.left);
System.out.print(tree.value + " ");
inOrder(tree.right);
}
/**
* 二叉树中序遍历的循环实现
*
* @param tree
*/
public static void inOrderLoop(BinaryTreeNode tree) {
if (tree == null)
return;
Stack<BinaryTreeNode> stack = new Stack<BinaryTreeNode>();
BinaryTreeNode node = tree;
while (node != null || !stack.empty()) {
if (node != null) {
stack.push(node);
node = node.left;
} else {
BinaryTreeNode item = stack.pop();
System.out.print(item.value + " ");
node = item.right;
}
}
}
// 后序遍历
public static void postOrder(BinaryTreeNode tree) {
if (tree == null)
return;
postOrder(tree.left);
postOrder(tree.right);
&n