題目
從上到下列印出二叉樹的每個節點,同一層的節點按照從左到右的順序列印,
例如:
給定二叉樹: [3,9,20,null,null,15,7],

回傳:
[3,9,20,15,7]
提示:
節點總數 <= 1000
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof
解題思路
本質上就是二叉樹的層序遍歷,使用佇列解決
注意點:
層序遍歷獲取到的值事先不知道size,所以需要使用一個ArrayList作為臨時存盤,然后在把ArrayList中的值賦值給陣列
代碼
/**
* 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];
}
// 用來臨時存盤
ArrayList<Integer> tempList = new ArrayList<>();
// 佇列
LinkedList<TreeNode> queue = new LinkedList<>();
queue.add(root);
// 回圈
while (!queue.isEmpty()) {
// 獲取佇列的size,回圈
int size = queue.size();
while (size > 0) {
TreeNode node = queue.poll();
tempList.add(node.val);
// 分別添加左子樹和右子樹到佇列中
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
size--;
}
}
// 創建回傳的陣列,回圈賦值
int[] array = new int[tempList.size()];
for (int i = 0; i < tempList.size(); i++) {
array[i] = tempList.get(i);
}
return array;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/179116.html
標籤:其他
上一篇:數學模型作業(3)
