当前位置:网站首页>JS force deduction brush question 102 Sequence traversal of binary tree

JS force deduction brush question 102 Sequence traversal of binary tree

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

var levelOrder = function(root) {
    let rear = [];// Traversal queue 
    let answers = [];// Two dimensional array 
    if(!root)return answers;// A special case 
    rear.push(root);// Root in line 
    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();
            answer.push(tmp.val);
            if(tmp.left)rear.push(tmp.left);
            if(tmp.right)rear.push(tmp.right);
        }
        answers.push(answer);
    }
    return answers;
};

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