有序二叉树层次遍历

版权声明:欢迎关注一起交流学习,个人 github: https://github.com/luoqifei https://blog.csdn.net/aa5305123/article/details/81941621

   遍历有序二叉树,顺序输出每一层node 的data。

  比如二叉树

             6

    3             9

1     5     7         10

打印输出就是,6,3,9,1,5,7,10。

这个利用队列实现非常高效。

package dayscode;


import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

/**
 * 二叉树层次遍历打印输出
 */
public class BSTTraversal {
    static class Node {
        Node left, right;
        int data;

        Node(int data) {
            this.data = data;
            left = right = null;
        }
    }

    public static Node insert(Node root, int data) {
        if (root == null) {
            return new Node(data);
        }
        Node cur;
        if (data <= root.data) {
            cur = insert(root.left, data);
            root.left = cur;
        }
        else{
            cur = insert(root.right, data);
            root.right = cur;
        }
        return root;
    }

    static void levelOrder(Node root) {
        Queue<Node> elements = new LinkedList();//利用队列先进先出
        elements.offer(root);
        while (!elements.isEmpty()) {//队列循环输出
            Node tmp = elements.poll();
            System.out.print(tmp.data + " ");
            if (tmp.left != null) {
                elements.offer(tmp.left);
            }
            if (tmp.right != null) {
                elements.offer(tmp.right);
            }
        }
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();
        Node root = null;
        while (T-- > 0) {
            int data = sc.nextInt();
            root = insert(root, data);
        }
        levelOrder(root);
    }
}

猜你喜欢

转载自blog.csdn.net/aa5305123/article/details/81941621