二叉树-先序遍历

//二叉树先遍历
public class Node{
    public int value;
    public Node left;
    public Node right;
    public Node(int data){
        this.value=data;
    }
}

//递归实现二叉树先序遍历
public void preOrderRecur(Node head){
    if(head==null){
        return;
    }
    System.out.println(head.value + " ");
    preOrderRecur(head.left);
    preOrderRecur(head.right);
}

//非递归实现二叉树先序遍历
public void preOrderUnRecur(Node head){
    System.out.println("pre-order: ");
    if(head!=null){
        Stack<Node> stack=new Stack<Node>();
        stack.add(head);
        while(!stack.isEmpty()){
            head=stack.pop();
            System.out.println(head.value + " ");
            if(head.right!=null){
                stack.push(head.right);
            }
            if(head.left!=null){
                stack.push(head.left);
            }
        }
    }
    System.out.println();
}

猜你喜欢

转载自blog.csdn.net/weixin_42146769/article/details/88422728