public int[] levelOrder(TreeNode root) { // 广度优先借助队列 Queue<TreeNode> queue = new LinkedList<>(); ArrayList<Integer> ans = new ArrayList<>(); while (root != null){ ans.add(root.val); // 判断是否有左右子树,有则进队列 if (root.left != null){ queue.offer(root.left); } if (root.right != null){ queue.offer(root.right); } // 先进先出原则 root = queue.poll(); } int[] res = new int[ans.size()]; for (int i = 0; i < res.length ; i++){ res[i] = ans.get(i); } return res; }
剑指Offer-30从上到下打印二叉树
最新推荐文章于 2022-11-14 17:21:43 发布