标签:
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 { public List<List<Integer>> levelOrderBottom(TreeNode root) { //跟正常的层序遍历的不同,在放入结果时,头插法 List<List<Integer>> res=new ArrayList<List<Integer>>(); List<Integer> seq=new ArrayList<Integer>(); if(root==null) return res; int curLevel=1; int nextLevel=0; LinkedList<TreeNode> queue=new LinkedList<TreeNode>();//如果是List,有问题,会显示remove方法找不到 queue.add(root); while(!queue.isEmpty()){ TreeNode node=queue.remove(); seq.add(node.val); curLevel--; if(node.left!=null){ queue.add(node.left); nextLevel++; } if(node.right!=null){ queue.add(node.right); nextLevel++; } if(curLevel==0){ res.add(0,seq); curLevel=nextLevel; nextLevel=0; seq=new ArrayList<Integer>(); } } return res; } }
[leedcode 107] Binary Tree Level Order Traversal II
标签:
原文地址:http://www.cnblogs.com/qiaomu/p/4665851.html