200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > 【简洁写法】剑指 Offer 32 - I. 从上到下打印二叉树

【简洁写法】剑指 Offer 32 - I. 从上到下打印二叉树

时间:2023-12-21 21:19:13

相关推荐

【简洁写法】剑指 Offer 32 - I. 从上到下打印二叉树

立志用最少的代码做最高效的表达

从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。

例如:

给定二叉树: [3,9,20,null,null,15,7],

返回:

[3,9,20,15,7]

提示:

节点总数 <= 1000

层序遍历。

/*** Definition for a binary tree node.* public class TreeNode {*int val;*TreeNode left;*TreeNode right;*TreeNode(int x) { val = x; }* }*/class Solution {public int[] levelOrder(TreeNode root) {if(root == null) return new int[0];List<Integer> list = new ArrayList<>();Queue<TreeNode> queue = new ArrayDeque<>();queue.add(root);while(!queue.isEmpty()) {TreeNode tmp = queue.remove();list.add(tmp.val);if(tmp.left != null) queue.add(tmp.left);if(tmp.right != null) queue.add(tmp.right);}return list.stream().mapToInt(Integer::intValue).toArray();}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。