import java.util.Stack;
public class RecursiveBinaryTree {
private static class Node{
private Integer data;
private Node left;
private Node right;
public Node() {
}
public Node(Integer data) {
this.data = data;
}
}
//利用栈先序遍历二叉树
public static void pre(Node node){
Stack<Node> stack = new Stack();
stack.push(node);
while (!stack.isEmpty()){
node = stack.pop();
System.out.println(node.data);
if(node.right != null){
stack.push(node.right);
}
if (node.left != null){
stack.push(node.left);
}
}
}
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
pre(root);
System.out.println("-------------");
}
}
利用栈先序遍历二叉树
最新推荐文章于 2024-09-15 19:46:31 发布