zoukankan      html  css  js  c++  java
  • 103. Binary Tree Zigzag Level Order Traversal(js)

    103. Binary Tree Zigzag Level Order Traversal

    Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

    For example:
    Given binary tree [3,9,20,null,null,15,7],

        3
       / 
      9  20
        /  
       15   7
    

    return its zigzag level order traversal as:

    [
      [3],
      [20,9],
      [15,7]
    ]
    题意:二叉搜索树的层序遍历的变形,z形遍历
    代码如下:
    /**
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {TreeNode} root
     * @return {number[][]}
     */
    var zigzagLevelOrder = function(root) {
        let res=[];
       helper(root,res,0);
        return res;
    };
    
    var helper=function(root,res,level){
        if(!root) return ;
        if(!res[level]) res[level]=[];
        level%2 ? res[level].unshift(root.val) :res[level].push(root.val);
        helper(root.left,res,level+1);
        helper(root.right,res,level+1);
    }
  • 相关阅读:
    elk 分布式数据同步
    mget 同时获取
    Jzoj1460 无题noname
    Jzoj1460 无题noname
    Jzoj1322硬币
    Jzoj1322硬币
    Jzoj1321 灯
    Jzoj1321 灯
    Jzoj1310 生日礼物
    Jzoj1310 生日礼物
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10713062.html
Copyright © 2011-2022 走看看