題目
給你二叉樹的根節(jié)點?root
?,返回其節(jié)點值的?層序遍歷?。 (即逐層地,從左到右訪問所有節(jié)點)。
示例 1:
輸入:root = [3,9,20,null,null,15,7] 輸出:[[3],[9,20],[15,7]]
示例 2:
輸入:root = [1] 輸出:[[1]]
示例 3:
輸入:root = [] 輸出:[]
提示:文章來源:http://www.zghlxwxcb.cn/news/detail-618808.html
- 樹中節(jié)點數(shù)目在范圍?
[0, 2000]
?內(nèi) -1000 <= Node.val <= 1000
解答
源代碼
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
Queue<TreeNode> queue = new ArrayDeque<>();
if (root != null) {
queue.offer(root);
}
while (!queue.isEmpty()) {
List<Integer> combine = new ArrayList<>();
int len = queue.size();
for (int i = 0; i < len; i++) {
TreeNode q = queue.poll();
combine.add(q.val);
if (q.left != null) {
queue.offer(q.left);
}
if (q.right != null) {
queue.offer(q.right);
}
}
res.add(combine);
}
return res;
}
}
總結(jié)
之前做的題里深度優(yōu)先遍歷(DFS)用得比較多,主要是回溯算法,這道題的層序遍歷需要用到廣度優(yōu)先遍歷(BFS),使用的是隊列。需要注意的一點是層序遍歷是每一層為一組,所以每次遍歷一層時需要先記下當前層有多少節(jié)點,遍歷完這個數(shù)量的節(jié)點之后才能進入下一次的遍歷。文章來源地址http://www.zghlxwxcb.cn/news/detail-618808.html
到了這里,關(guān)于【LeetCode】102.二叉樹的層序遍歷的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!