package sort;
import java.util.Stack;
public class Test32_3 {
public static void main(String[] args) {
int deepth = 3;
// int rootvalue=1;
BinayTreeNode root = new BinayTreeNode(1, null, null);
makeTree(root, deepth);
printTree(root);
}
private static void printTree(BinayTreeNode root) {// 需要两个栈
// TODO Auto-generated method stub
Stack<BinayTreeNode> stack1 = new Stack<BinayTreeNode>();
Stack<BinayTreeNode> stack2 = new Stack<BinayTreeNode>();
stack1.push(root);// 首先将元素放入其中一个栈中
while (!stack1.isEmpty() || !stack2.isEmpty()) { // 如果两个栈中某个栈还有元素就继续
if (!stack1.isEmpty() && stack2.isEmpty()) {// 栈1不空,去栈顶元素,输出节点值,然后把根节点的左节点和右节点分别放入栈2
// 中
while (!stack1.isEmpty()) {// 注意放先放左节点再放右节点
BinayTreeNode temp = stack1.pop();
System.out.println(temp.value + " ");
if (temp.left != null)
stack2.push(temp.left);
if (temp.right != null)
stack2.push(temp.right);
}
}
if (!stack2.isEmpty() && stack1.isEmpty()) {// 栈2不空,去栈顶元素,输出节点值,然后把根节点的右节点和左节点分别放入栈2
// 中
while (!stack2.isEmpty()) {// 注意放先放右节点再放左节点
BinayTreeNode temp = stack2.pop();
System.out.println(temp.value + " ");
if (temp.right != null)
stack1.push(temp.right);
if (temp.left != null)
stack1.push(temp.left);
}
}
}
}
private static void makeTree(BinayTreeNode node, int deep) {
// TODO Auto-generated method stub
if (deep > 0) {
node.left = new BinayTreeNode(node.value * 2, null, null);
node.right = new BinayTreeNode(node.value * 2 + 1, null, null);
makeTree(node.left, deep - 1);
makeTree(node.right, deep - 1);
}
}
}
二叉树层次遍历算法
本文介绍了一种使用双栈实现的二叉树层次遍历算法,通过交替使用两个栈来实现从左到右和从右到左的层次遍历,展示了如何构造二叉树并打印其层次结构。
387

被折叠的 条评论
为什么被折叠?



