102-Binary Tree Level Order Traversal
Description
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]
]
問題描述
給定二叉樹, 返回其層級遍歷的值
問題分析
解法1(BFS)
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> wrapList = new LinkedList();
if(root == null) return wrapList;
Queue<TreeNode> queue = new LinkedList();
queue.offer(root);
while(!queue.isEmpty()){
int levelNum = queue.size();
List<Integer> subList = new LinkedList();
for(int i = 0; i < levelNum; i++) {
if(queue.peek().left != null) queue.offer(queue.peek().left);
if(queue.peek().right != null) queue.offer(queue.peek().right);
subList.add(queue.poll().val);
}
wrapList.add(subList);
}
return wrapList;
}
}
解法2(DFS)
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList();
levelTraverse(root, 0, res);
return res;
}
private void levelTraverse(TreeNode root, int depth, List<List<Integer>> res) {
if(root == null) return;
if(res.size() == depth) res.add(new ArrayList());
res.get(depth).add(root.val);
levelTraverse(root.left, depth + 1, res);
levelTraverse(root.right, depth + 1, res);
}
}
相關文章
- Binary Tree Level Order Traversal [LEETCODE]LeetCode
- Binary-tree-level-order-traversal
- 103. Binary Tree Zigzag Level Order Traversal
- 107-Binary Tree Level Order Traversal II
- [LintCode] Binary Tree Level Order
- [leetcode]binary-tree-inorder-traversalLeetCode
- LeetCode | 144. Binary Tree Preorder TraversalLeetCode
- LeetCode | 145. Binary Tree Postorder TraversalLeetCode
- Leetcode 94. Binary Tree Inorder TraversalLeetCode
- Leetcode 144. Binary Tree Preorder TraversalLeetCode
- Leetcode 145. Binary Tree Postorder TraversalLeetCode
- LeetCode 272 Closest Binary Tree Traversal II 解題思路LeetCode
- LeetCode之Increasing Order Search Tree(Kotlin)LeetCodeKotlin
- PG12-2 B-Tree 索引 level 0 root頁索引
- PG 12-2 B-Tree 索引 分析 分裂 level = 1索引
- The order of a Tree (二叉搜尋樹+先序遍歷)
- Traversal of trees
- P10013 [集訓隊互測 2023] Tree Topological Order Counting
- Server-side vulnerabilities :path traversalServerIDE
- Level Up
- CSS orderCSS
- 記一次kafka的high level和low levelKafka
- Order by 優化優化
- order by與索引索引
- natas(level0-level14)通關詳細指南(一)
- E. Level Up
- E - Level K Palindrome
- CSS LEVEL4CSS
- [Javascript] Object property orderJavaScriptObject
- MySQL 之 ORDER BY FIELDMySql
- mysql order by 優化MySql優化
- CSS3 orderCSSS3
- tree
- BUU_jarvisoj_level0JAR
- RuneScape - To verify your level of combatBAT
- FUNBOX-5: NEXT LEVEL
- MySql ORDER BY索引是否失效MySql索引
- MySQL, Incorrect usage of UNION and ORDER BYMySql