二叉树的非递归遍历和层次遍历,利用栈和队列来实现

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  public static void inOrder2(Node node) {
        Stack<Node> stack = new Stack<>();
        Node p = node;
        while (p != null || !stack.isEmpty()) {
            if (p != null) {
                stack.push(p);
                p = p.left;
            } else {
                p = stack.pop();
                System.out.println(p.data);
                p = p.right;
            }
        }
    }

    public static void levelOrder(Node node) {
        Queue<Node> queue = new LinkedList<>();
        Node p;
        queue.add(node);
        while (!queue.isEmpty()) {
            p = queue.poll();
            System.out.println(p.data);
            if (p.left != null) {
                queue.add(p.left);
            }
            if (p.right != null) {
                queue.add(p.right);
            }
        }
    }

  

posted on 2020-08-26 22:35  lkjhgfdsa123  阅读(468)  评论(0编辑  收藏  举报