Binary Tree Level Order Traversal II @ LeetCode

Source: Internet
Author: User
Tags tree serialization

Level Order Traversal of the tree and ArrayList flip

Package Level3; import java. util. arrayList; import java. util. using list; import java. util. queue; import Utility. treeNode;/*** Binary Tree Level Order Traversal II *** Given a binary tree, return the bottom-up level order traversal of its nodes 'values. (ie, from left to right, level by level from leaf to root ). for example: Given binary tree {, 20, #, #,}, 3/\ 9 20/\ 15 7 return its botto M-up level order traversal as: [[15, 7] [9, 20], [3],] 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 S107 {public static void main (String [] args) {} public ArrayLis T <ArrayList <Integer> levelOrderBottom (TreeNode root) {ArrayList <Integer> ret = new ArrayList <Integer> (); if (root = null) {return ret;} Queue <TreeNode> queue = new queue list <TreeNode> (); Queue. add (root); ArrayList <Integer> alal = new ArrayList <Integer> (); ArrayList <Integer> al = new ArrayList <Integer> (); // record the number of nodes at the current level and next level int currentLeve L = 1; int nextLevel = 0; 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) {alal. add (al); al = new ArrayList <Integer> (); currentLevel = nextLevel; nextLevel = 0 ;}// flip ArrayList for (int I = alal. size ()-1; I> = 0; I --) {ret. add (alal. get (I) ;}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.