102. 二叉树的层次遍历

题目:
在这里插入图片描述
题解:
思路:递归,追踪树的层次。
代码:

var levelOrder = function (root) {
    var res = []
    let index = 0;
    travel(root, index)

    function travel(roots, index) {
        if (roots) {
            if (!res[index]) {
                res[index] = [];
            }
            res[index].push(roots.val)
            index += 1;
            travel(roots.left, index)
            travel(roots.right, index)
        }
    }

    return res
};

(ps:第二周,第四天)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章