非递归方式实现的二叉树的遍历

中序遍历是 左--》中--》右的顺序,可以考虑先找到所有左节点,然后按照先进后出栈的结构来实现。

先来一个简单的二叉树。

     

public class BinarySearchTree {

    Node root;

    public void add(Integer value){
        if(root == null){
            root = new Node(value);
            return;
        }

        Node parent = root;
        Node current = root;
        while(current != null){
            if(current.value == value){
                return;
            }
            parent = current;
            if(current.value < value){
                current = current.right;
            }else if(current.value > value){
                current = current.left;
            }
        }

        if(parent.value > value){
            parent.left = new Node(value);
        }else {
            parent.right = new Node(value);
        }
    }



    public static class Node{
        Node left;
        Node right;
        Integer value;

        public Node(Integer value) {
            this.value = value;
        }
    }

}

   再来实现非递归的中序遍历

public class BinaryTreeTraverse {

    public static void main(String[] args) {
        BinarySearchTree bst = new BinarySearchTree();
        bst.add(3);
        bst.add(5);
        bst.add(1);
        bst.add(8);
        bst.add(4);
        bst.add(6);
        bst.add(7);
        inOrderTraverse(bst);
    }


    public static void inOrderTraverse(BinarySearchTree bst){
        Stack<BinarySearchTree.Node> stack = new Stack<>();
        BinarySearchTree.Node temp = bst.root;
        while(!stack.isEmpty() || temp != null){
            while(temp != null){
                stack.add(temp);
                temp = temp.left;
            }

            BinarySearchTree.Node pop = stack.pop();
            System.out.println(pop.value);
            temp = pop.right;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值