LeetCode 103. Binary Tree Zigzag Level Order Traversal — JavaScript

裴裴來台灣,瑟瑟發抖,希望這幾天平平安安~
function zigzagLevelOrder(root) {
let res = [];
go(root, 0, res);
return res;
}
function go(node, l, res) { // l means level
if (!node) return;
if (!res[l]) {
res.push([]);
}

if (l % 2 === 0) {
res[l].push(node.val);
} else {
res[l].unshift(node.val);
}

go(node.left, l+1, res);
go(node.right, l+1, res);
}

題目要求每一層依序由左到右,再來由右到左,推入陣列中即可。

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
黃韋智

自學寫程式,目前爲 React 前端工程師。熱愛旅遊,將近 30 個國家,足跡遍佈亞洲與歐洲。生命與街舞已經離不開,歡迎訂閱 Youtube 頻道:https://www.youtube.com/channel/UCEU-bEDl7R-iGyLVZFae33g