LeetCode -- Binary Tree Level Order Traversal II
Question:
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 {3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
Analysis:
问题描述:给出一棵二叉树,写出它的从底层到最上层的层次遍历。
思路一:一个投机取巧的思路,前面做了从上层到下层的遍历,二者的不同之处仅在于返回的列表的顺序,因此先从上到下遍历,然后将外层列表倒转一下即可。。
/** * 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>> res = new ArrayList<List<Integer>>(); List<Integer> l = new ArrayList<Integer>(); if(root == null) return res; if(root.left == null && root.right == null) { l.add(root.val); res.add(l); return res; } TreeNode start; //记录了每一层的开始 Queue<TreeNode> node = new LinkedList<TreeNode>(); node.offer(root); while(!node.isEmpty()) { TreeNode cur = node.peek(); List<Integer> thisLevel = new ArrayList<Integer>(); start = null; while(node.peek() != start && !node.isEmpty()) { cur = node.poll(); if(start == null) { if(cur.left != null) start = cur.left; else if(cur.right != null) start = cur.right; } thisLevel.add(cur.val); if(cur.left != null) node.offer(cur.left); if(cur.right != null) node.offer(cur.right); } res.add(thisLevel); } List<List<Integer>> res1 = new ArrayList<List<Integer>>(); for(int i=0; i<res.size(); i++) { res1.add(res.get(res.size() - 1 - i)); } return res1; } }