LeetCode 331. Verify Preorder Serialization of a Binary Tree — JavaScript solution

狗勾都比我厲害ㄇ嗚嗚嗚
var isValidSerialization = function(preorder) {
const stack = [0];
const arr = preorder.split(',');
for(let item of arr) {
if(item === '#') stack[stack.length-1]++;
else stack.push(0);
while(stack.length > 1 && stack[stack.length-1] === 2) {
stack.pop();
stack[stack.length-1]++
}
}
return stack.length === 1 && stack.pop() === 1;
};

1 代表一個左子樹,2 代表左右子樹,因此可以消除,向父節點加上 1,消除到最後只會剩下一開始放入的 0 在 stack 中,並且最後被加上了 1

--

--

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