队列和栈相关例题

发布时间:2024年01月19日

4.队列

1.1二叉树的层序遍历


public class BinaryTree {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(
                new TreeNode(
                        new TreeNode(4),
                        new TreeNode(5),
                        2),
                new TreeNode(
                        new TreeNode(6),
                        new TreeNode(7),
                        3),
                1);
        //方式1
        print1(root);
        //方式2
        List<List<Integer>> list = print2(root);
    }
    public static List<List<Integer>> print2(TreeNode root){
        List<List<Integer>>list=new ArrayList<>();
        if(root==null){
            return list;
        }
        LinkedListQueue<TreeNode> queue = new LinkedListQueue<>();
        queue.offer(root);
        int count1 = 1;
        while (!queue.isEmpty()) {
            List<Integer>leave=new ArrayList<>();
            int count2 = 0;//下层节点数
            for (int i = 0; i < count1; i++) {
                TreeNode pool = queue.pool();
                leave.add(pool.val);
                System.out.print(pool + "  ");
                if (pool.left != null) {
                    queue.offer(pool.left);
                    count2++;
                }
                if (pool.right != null) {
                    queue.offer(pool.right);
                    count2++;
                }
            }
            System.out.println();
            list.add(leave);
            count1=count2;
        }
        return list;
    }
    public static void print1(TreeNode root){
        LinkedListQueue<TreeNode> queue = new LinkedListQueue<>();
        queue.offer(root);
        int count1 = 1;
        while (!queue.isEmpty()) {
            int count2 = 0;//下层节点数
            for (int i = 0; i < count1; i++) {
                TreeNode pool = queue.pool();
                System.out.print(pool + "  ");
                if (pool.left != null) {
                    queue.offer(pool.left);
                    count2++;
                }
                if (pool.right != null) {
                    queue.offer(pool.right);
                    count2++;
                }
            }
            System.out.println();
            count1=count2;
        }
    }
    static class TreeNode {
        TreeNode left;
        TreeNode right;
        int val;

        public TreeNode(int val) {
            this.val = val;
        }
        public TreeNode(TreeNode left, TreeNode right, int val) {
            this.left = left;
            this.right = right;
            this.val = val;
        }
        @Override
        public String toString() {
            return String.valueOf(this.val);
        }
    }
}

y

文章来源:https://blog.csdn.net/weixin_67852890/article/details/135696790
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。