标签:binarytree orderlevel traversal java
题目:
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] ]
题解:
这题这102题(我上一篇博客)几乎是一模一样的,所有我只改动了一行代码, result.add(tempReslut)改为了result.add(0,tempReslut);
代码:
public static List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> result=new ArrayList<List<Integer>>();//返回的最终结果 Queue<TreeNode> treeNodes2=new LinkedList<>();//用来存放每一层的节点 //处理第一个节点(root) if(root==null) return result; else { List<Integer> temp=new ArrayList<>();//存放暂时的结果 temp.add(root.val); treeNodes2.offer(root); result.add(temp); } while(!treeNodes2.isEmpty()) { int i=treeNodes2.size(); List<Integer> tempReslut=new ArrayList<>();//存放暂时的结果 while(i>0)//遍历这一层的所有节点 { TreeNode tNode=treeNodes2.poll(); if(tNode.left!=null) { tempReslut.add(tNode.left.val); treeNodes2.offer(tNode.left); } if(tNode.right!=null) { tempReslut.add(tNode.right.val); treeNodes2.offer(tNode.right); } i--; } if(!tempReslut.isEmpty()) result.add(0,tempReslut); } return result; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
LeetCode107 Binary Tree Level Order Traversal II
标签:binarytree orderlevel traversal java
原文地址:http://blog.csdn.net/u012249528/article/details/46779293