sisterAn / JavaScript-Algorithms

基础理论+JS框架应用+实践,从0到1构建整个前端算法体系
5.51k stars 634 forks source link

leetcode102:二叉树的层序遍历 #47

Open sisterAn opened 4 years ago

sisterAn commented 4 years ago

给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。 

示例: 二叉树:[3,9,20,null,null,15,7] ,

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

[
  [3],
  [9,20],
  [15,7]
]
plane-hjh commented 4 years ago

这道题和二叉树的层次遍历相似,只需要把 reverse() 去除就可以了

广度优先遍历

var levelOrder = function(root) {
    if(!root) return []
    let res = [], 
        queue = [root]
    while(queue.length) {
        let curr = [],
            temp = []
        while(queue.length) {
            let node = queue.shift()
            curr.push(node.val)
            if(node.left) temp.push(node.left)
            if(node.right) temp.push(node.right)
        }
        res.push(curr)
        queue = temp
    }
    return res
};

深度优先遍历

var levelOrder = function(root) {
    const res = []
    var dep = function (node, depth){
        if(!node) return
        res[depth] = res[depth]||[]
        res[depth].push(node.val)
        dep(node.left, depth + 1)
        dep(node.right, depth + 1)
    }
    dep(root, 0)
    return res
};
AnranS commented 4 years ago
var levelOrder = function(root) {
    let res = [], queue = [];
    if(!root) return res;
    queue.push(root);

    while(queue.length) {
        let len = queue.length;
        res.push([]);
        for(let i = 0;i<len;i++) {
            let node = queue.shift();
            res[res.length - 1].push(node.val);
            if(node.left) queue.push(node.left);
            if(node.right) queue.push(node.right);
        }
    }
    return res;
};
lewisYe commented 3 years ago

使用广度优先遍历 然后再对数据进行分层

var levelOrder = function(root) {
    if(!root || root.val == null) return []
   let queue = []
   let res = []
   queue.push(root)
   while(queue.length){
       let len = queue.length
       let curr = []
       for(var i =0;i<len;i++){
           let node = queue.shift()
           curr.push(node.val)
            if(node.left)queue.push(node.left)
            if(node.right)queue.push(node.right)
       }
       res.push(curr)
   }
    return res
};