本文共 877 字,大约阅读时间需要 2 分钟。
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,null,null,15,7], return its bottom-up level order traversal as: [[15,7],[9,20],[3]]
从第一层开始,每次读一个sublist,读完之后将其弹出,再将新一层的节点读入,像队列一样,代码如下:
public class Solution { public List
> levelOrderBottom(TreeNode root) { List
> list = new ArrayList
> (); if(root == null) return list; Queue queue = new LinkedList (); queue.add(root); while(queue.size() > 0) { List sublist = new ArrayList (); int tempSize = queue.size(); for(int i = 0; i < tempSize; i++) { TreeNode node = queue.poll(); sublist.add(node.val); if(node.left != null) queue.add(node.left); if(node.right != null) queue.add(node.right); } list.add(0, sublist); } return list; }}
转载地址:http://znjgj.baihongyu.com/