Binary Tree Zigzag Level Order Traversal @ LeetCode

Source: Internet
Author: User

It is also a variant of Level Order Traversal. It can be seen that it is necessary to write Level Order Traversal skillfully!

Package Level4; import java. util. arrayList; import java. util. collections; import java. util. using list; import java. util. queue; import Utility. treeNode;/*** 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 ). for example: Given binary tr Ee {3, 9, 20, #, #, 15, 7}, 3/\ 9 20/\ 15 7 return its zigzag level order traversal as: [[3], [20, 9], [15, 7] confused what "{1, #, 2, 3}" means?> Read more on how binary tree is serialized on OJ. OJ's Binary Tree Serialization: The serialization of a binary tree follows a level order traversal, where '# 'signiies a path terminator where no node exists below. here's an example: 1/\ 2 3/4 \ 5 The above binary tree is serialized as "{, 3, #,#, 4, #,#, 5 }". */public class S103 {public static void main (String [] args) {} public ArrayList <ArrayList <Integer> zigzagLevelOrder (TreeNode root) {ArrayList <Integer> ret = new ArrayList <Integer> (); if (root = null) {return ret;} Queue <TreeNode> queue = new queue list <TreeNode> (); ArrayList <Integer> al = new ArrayList <Integer> (); Queue. add (root); int currentLevel = 1; int nextLevel = 0; boolean left = true; while (! Queue. isEmpty () {TreeNode cur = queue. remove (); currentLevel --; al. add (cur. val); if (cur. left! = Null) {queue. add (cur. left); nextLevel ++;} if (cur. right! = Null) {queue. add (cur. right); nextLevel ++;} if (currentLevel = 0) {if (! Left) {// when right to left, you need to flip al Collections. reverse (al);} left =! Left; ret. add (al); al = new ArrayList <Integer> (); currentLevel = nextLevel; nextLevel = 0 ;}} return ret ;}}

 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.