429. N-ary Tree Level Order Traversal
Given an n-ary tree, return the level order traversal of its nodes" values. (ie, from left to right, level by level).
For example, given a 3-ary tree:
We should return its level order traversal:
[ [1], [3,2,4], [5,6] ]
Note:
The depth of the tree is at most 1000.
The total number of nodes is at most 5000.
use Queue, in each level, use queue.size() to loop
class Solution { public List102. Binary Tree Level Order Traversal> levelOrder(Node root) { List
> res = new ArrayList<>(); if (root == null) return res; Queue
queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { List curRes = new ArrayList<>(); int size = queue.size(); for (int i = 0; i < size; i++) { Node node = queue.poll(); curRes.add(node.val); for (Node child: node.children) { queue.offer(child); } } res.add(curRes); } return res; } }
Given a binary tree, return the level order traversal of its nodes" values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3 / 9 20 / 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]Solution (Iteration)
class Solution { public List> levelOrder(TreeNode root) { List
> res = new ArrayList<>(); if (root == null) return res; Queue
queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { List curRes = new ArrayList<>(); int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode node = queue.poll(); curRes.add(node.val); if (node.left != null) queue.offer(node.left); if (node.right != null) queue.offer(node.right); } res.add(curRes); } return res; } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/77375.html
摘要:题目要求对叉树进行水平遍历,并输出每一行遍历的结果。因此无需再用队列来额外存储每一行的水平遍历,可以直接通过递归将遍历结果插入到相应行的结果集中。 题目要求 Given an n-ary tree, return the level order traversal of its nodes values. (ie, from left to right, level by level)...
摘要:题目链接题目分析按层遍历叉树。思路以层数为键,塞入当前节点的值。最终代码若觉得本文章对你有用,欢迎用爱发电资助。 D55 429. N-ary Tree Level Order Traversal 题目链接 429. N-ary Tree Level Order Traversal 题目分析 按层遍历N叉树。 思路 以层数为键,塞入当前节点的值。 递归遍历即可。 最终代码
摘要:按顺序放入,正好方面是从到,顺序方面是从最右到最左,因为是先入后出。这样最后一下就是先左后右,先子后根。 590. N-ary Tree Postorder Traversal Problem Given an n-ary tree, return the postorder traversal of its nodes values.For example, given a 3-ar...
589. N-ary Tree Preorder Traversal Given an n-ary tree, return the preorder traversal of its nodes values.For example, given a 3-ary tree:showImg(https://segmentfault.com/img/bVbhKkv?w=781&h=502);Retu...
摘要:题目链接题目分析维数组的先序遍历。这题也不想多说什么了。是比较基础的题目了。先序就是先根后子而已。思路在遍历子节点之前,先保存当前节点的信息。最终代码若觉得本文章对你有用,欢迎用爱发电资助。 D43 589. N-ary Tree Preorder Traversal 题目链接 589. N-ary Tree Preorder Traversal 题目分析 N维数组的先序遍历。 这题也...
阅读 4076·2023-04-26 02:40
阅读 2624·2023-04-26 02:31
阅读 2709·2021-11-15 18:08
阅读 540·2021-11-12 10:36
阅读 1380·2021-09-30 09:57
阅读 5069·2021-09-22 15:31
阅读 2599·2019-08-30 14:17
阅读 1225·2019-08-30 12:58