二叉树层级遍历

题目: 有二叉树如下, 按层级输出结果: [[3], [9, 20], [15, 7]]

    3
   / \
  9  20
    /  \
   15   7
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */

原题链接: https://leetcode-cn.com/problems/binary-tree-level-order-traversal/

解法1: 基于DFS

遍历时,添加第二个参数,记录层级深度

function levelOrder(root) {
    let arr = [];
    if(!root) {
        return []
    }
    function dfs(node, level) {
        if(!arr[level]) {
            arr[level] = [];
        }
        arr[level].push(node.val);

        if(node.left) {
            dfs(node.left, level+1);
        }
        if(node.right) {
            dfs(node.right, level + 1);
        }
    }
    dfs(root, 0);
    return arr;
};

解法2:基于BFS

function bfs(tree) {
    let arr = [];
    let res = [];
    let count  = 0;
    
    arr.push([tree]);

    while(count < arr.length) {
        const nodeArr = arr[count++];
        res.push(nodeArr.map(n => n.val));

        const nextLevelNodes = nodeArr.reduce((prev, cur) => {
            if(cur.left){
                prev.push(cur.left);
            }
            if(cur.right) {
                prev.push(cur.right);
            }
            return prev;
        }, []);

        if(nextLevelNodes.length) {
            arr.push(childNodeArr);
        }
    }
    return res;
}

你可能感兴趣的:(二叉树层级遍历)