博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
lintcode-medium-Binary Tree Zigzag Level Order Traversal
阅读量:4349 次
发布时间:2019-06-07

本文共 1704 字,大约阅读时间需要 5 分钟。

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).

Given binary tree {3,9,20,#,#,15,7},

3   / \  9  20    /  \   15   7

 

return its zigzag level order traversal as:

[  [3],  [20,9],  [15,7]]
/** * Definition of TreeNode: * public class TreeNode { *     public int val; *     public TreeNode left, right; *     public TreeNode(int val) { *         this.val = val; *         this.left = this.right = null; *     } * } */  public class Solution {    /**     * @param root: The root of binary tree.     * @return: A list of lists of integer include      *          the zigzag level order traversal of its nodes' values      */    public ArrayList
> zigzagLevelOrder(TreeNode root) { // write your code here ArrayList
> result = new ArrayList
>(); if(root == null) return result; LinkedList
curr = new LinkedList
(); LinkedList
next = new LinkedList
(); ArrayList
line = new ArrayList
(); boolean l2r = true; curr.offer(root); while(!curr.isEmpty()){ TreeNode temp = null; if(l2r){ temp = curr.pollLast(); line.add(temp.val); if(temp.left != null) next.offer(temp.left); if(temp.right != null) next.offer(temp.right); } else{ temp = curr.pollLast(); line.add(temp.val); if(temp.right != null) next.offer(temp.right); if(temp.left != null) next.offer(temp.left); } if(curr.isEmpty()){ curr = next; next = new LinkedList
(); result.add(new ArrayList
(line)); line = new ArrayList
(); l2r = !l2r; } } return result; }}

 

转载于:https://www.cnblogs.com/goblinengineer/p/5278893.html

你可能感兴趣的文章
pt-table-checksum解读【转】
查看>>
matlab中类的定义和使用
查看>>
NIO(2):Channel
查看>>
Consistent Hashing算法
查看>>
C++基础--完善Socket C/S ,实现客户端,服务器端断开重连
查看>>
lvs,nginx反向代理,虚拟主机
查看>>
jquip,更简洁的代码
查看>>
【OJ】PAT-A解题报告
查看>>
基础练习 回文数
查看>>
科普-- 白话HTTPS
查看>>
文档语法
查看>>
利用套接字实现进程通信一例
查看>>
linux中shell变量$#,$@,$0,$1,$2的含义解释
查看>>
常用的shell命令整理
查看>>
A Brief Introduction to the Design of UBIFS
查看>>
了解你的Linux系统:必须掌握的20个命令
查看>>
js setInterval 启用&停止
查看>>
knockoutJS学习笔记04:监控属性
查看>>
18.10.6 考试总结
查看>>
iptables防火墙网路安全实践配置
查看>>