Title Description:
Given a binary tree, return the bottom-up level order traversal of its nodes ' values. (ie, from the left-to-right, the level by level from the leaf to root).
For example:
Given binary Tree {3,9,20,#,#,15,7}
,
3 / 9 / 7
Return its bottom-up level order traversal as:
[ [15,7], [9,20], [3]]
Problem Solving Ideas:
Using the breadth-first search method, the queue method is used to traverse the leaf nodes of one layer at a time, and the leaves nodes of the next layer are added to the queue. Each time you traverse the end of a layer of nodes, the list of the layer nodes is placed before the list of the whole to achieve a bottom-to-high arrangement.
The code is as follows:
/** * Definition for a binary tree node. * public class TreeNode {* int val, * TreeNode left, * TreeNode right; * TreeNode (int x) {val = x;} *} */public class Solution {public list<list<integer>> levelorderbottom (TreeNode root) { list< list<integer>> list = new linkedlist<list<integer>> (); queue<treenode> queue = new linkedlist<treenode> (); if (root = null) return list; Queue.offer (root); while (!queue.isempty ()) { int num = Queue.size (); list<integer> levellist = new linkedlist<integer> (); for (int i = 0; i < num; i++) { if (Queue.peek (). Left! = null) Queue.offer (Queue.peek (). left); if (Queue.peek (). Right! = null) Queue.offer (Queue.peek (). right); Levellist.add (Queue.poll (). val); } List.add (0, levellist); } return list; }}
Java [Leetcode 107]binary Tree level Order traversal II