当前位置:网站首页>JS force deduction brush question 103 Zigzag sequence traversal of binary tree

JS force deduction brush question 103 Zigzag sequence traversal of binary tree

2022-04-23 13:56:00 Candy_ Rainbow_

var zigzagLevelOrder = function(root) {
    let rear = [];// Traversal queue 
    let answers = [];// Two dimensional array 
    if(!root)return answers;// A special case 
    rear.push(root);// Root in line 
    let flagStack = 1;// Single layer from left to right ( queue ) Double deck from right to left ( Stack )
    while(rear.length > 0){
        let answer = [];// Traversal layer by layer 
        let len = rear.length;// The queue length will change , Record the following 
        for(let i = 0; i < len; i++){
            let tmp = rear.shift();
            if(flagStack % 2 == 1)// Single layer from left to right ( queue )
                answer.push(tmp.val);
            else// Double deck from right to left ( Stack )
                answer.unshift(tmp.val);
            if(tmp.left)rear.push(tmp.left);
            if(tmp.right)rear.push(tmp.right);
        }
        answers.push(answer);
        flagStack++;
    }
    return answers;
};

版权声明
本文为[Candy_ Rainbow_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231353588755.html