算法热题:从上到下打印二叉树 I
每日简短一刷,保持手感系列
题目:从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
例如:给定二叉树: [3,9,20,null,null,15,7],
返回:[3,9,20,15,7]
根据题意就是一个广度优先搜索即 BFS,那么 BFS 常用队列来实现。
所以我们直接遍历二叉树,利用队列来存储节点,根据队列先入先出特性来即可完成按层且从左到右的顺序打印。
没什么花头,直接看代码,应该很好理解。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
classSolution{
publicint[] levelOrder(TreeNode root) {
if (root == null) {
returnnewint[0];
}
Queue<TreeNode> nodeQueue = new LinkedList();
nodeQueue.add(root);
List<Integer> list = new ArrayList();
while (!nodeQueue.isEmpty()) {
TreeNode node = nodeQueue.poll();
list.add(node.val);
if (node.left != null) {
nodeQueue.add(node.left);
}
if (node.right != null) {
nodeQueue.add(node.right);
}
}
int[] res = newint[list.size()];
for(int i = 0; i < list.size(); i++) {
res[i] = list.get(i);
}
return res;
}
}
时间复杂度 O(n)
空间复杂度 O(n)
一道中等难度题,不过能想到用队列来实现的话,应该不是很难
点击阅读原文即可练习。
添加微信:yes_oba,备注算法,即可进算法学习群。
关键词
节点
二叉树
算法
node.right
node.left
最新评论
推荐文章
作者最新文章
你可能感兴趣的文章
Copyright Disclaimer: The copyright of contents (including texts, images, videos and audios) posted above belong to the User who shared or the third-party website which the User shared from. If you found your copyright have been infringed, please send a DMCA takedown notice to [email protected]. For more detail of the source, please click on the button "Read Original Post" below. For other communications, please send to [email protected].
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。