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] ]
思路:此题和二叉树水平序类似,求解水平序之后再反转下链表即可。代码如下:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { List<List<Integer>> list; public List<List<Integer>> levelOrderBottom(TreeNode root) { list = new ArrayList<List<Integer>>(); //对list进行倒序排序 dfs(0,root); for(int i = 0; i+i < list.size()-1;i++){ List<Integer> al = list.get(i); list.set(i,list.get(list.size()-1-i)); list.set(list.size()-1-i,al); } return list; } private void dfs(int dep,TreeNode root){ if(root == null){ return; } List<Integer> al; if(list.size() > dep){ al = list.get(dep); }else{ al = new ArrayList<Integer>(); list.add(al); } dfs(dep+1,root.left); al.add(root.val); dfs(dep+1,root.right); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
leetCode 107.Binary Tree Level Order Traversal II (二叉树水平序)
原文地址:http://blog.csdn.net/xygy8860/article/details/47189679