III. 从上到下打印二叉树 III

85 阅读1分钟

III. 从上到下打印二叉树 III

题目描述:

请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。

例如:

给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

[
  [3],
  [20,9],
  [15,7]
]

解法:

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrder = function(root) {
    if(!root){
        return [];
    }
    const res=[];
    let temp=[root];
    let flag=true;
    while(temp.length!==0){
        const newVal=temp.map(item=>item.val);
        if(!flag){
            newVal.reverse();
        }
        res.push(newVal);
        flag=!flag;
        const newTemp=[];
        temp.forEach(item=>{
            if( item.left) newTemp.push(item.left);
            if( item.right) newTemp.push(item.right);
        })
        temp=[...newTemp]
    }
    return res;
};