题目描述
不知道这个比其它的解慢多少,求指点
JAVA 代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
class NodeHolder{
TreeNode node;
int layer;
public NodeHolder(TreeNode node, int layer) {
this.node = node;
this.layer = layer;
}
@Override
public String toString() {
return "NodeHolder{" +
"node=" + node +
", layer=" + layer +
'}';
}
}
public List<List<Integer>> printFromTopToBottom(TreeNode root) {
if (root == null){
return new ArrayList<>();
}
ArrayList<NodeHolder> list = new ArrayList<>();
Queue<NodeHolder> queue = new LinkedList<>();
queue.add(new NodeHolder(root,0));
while (!queue.isEmpty()){
NodeHolder holder = queue.poll();
list.add(holder);
if (holder.node.left != null){
queue.add(new NodeHolder(holder.node.left,holder.layer + 1));
}
if (holder.node.right != null){
queue.add(new NodeHolder(holder.node.right,holder.layer + 1));
}
}
// list的最后一个元素的layer属性就是高度
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i <= list.get(list.size() - 1).layer; i ++){
List<Integer> temp = new ArrayList<>();
for (NodeHolder holder : list) {
if (holder.layer == i){
temp.add(holder.node.val);
}
}
res.add(temp);
}
return res;
}
}