前言
掘金團隊号上線,助你 Offer 臨門! 點選
檢視詳情題目描述

解題思路
- 使用隊列的思想來進行層次周遊
- 數組隊列存儲目前節點的左右指針,然後将隊頭清除,知道隊列中的所有元素都被清空。
解題代碼
var levelOrder = function (root) {
if (root === null) return [];
const result = [];
const pointer = [root];
while (pointer.length !== 0) {
result.push(pointer[0].val);
if (pointer[0].left !== null) {
pointer.push(pointer[0].left);
}
if (pointer[0].right !== null) {
pointer.push(pointer[0].right);
}
pointer.shift();
}
return result;
};
作者:Always_positive
連結:https://juejin.cn/post/6948617192048951332
來源:稀土掘金
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
總結
- 本題屬于二叉樹的層次周遊問題
- 核心點在于使用隊列來存儲目前節點的左右子節點。
- 隊列的判斷條件是隊頭元素是否存在。