思路
用了一个for循环,比用两个for循环的复杂。
Level记录当前的层数;
map是存放节点的,key是节点,value是节点的层数。
每次队列取出节点时,就将节点的层数和当前记录的层数level比较,相等就是同一层,不等就让level++;
然后添加队列数据的时候,map也跟着添加数据即可。
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if(root == null){
return new ArrayList(new ArrayList());
}
List<List<Integer>> res = new ArrayList<>();
Queue<TreeNode> queue= new LinkedList<>();
queue.add(root);
TreeNode cur = root;
Map<TreeNode,Integer> map = new HashMap<>();
List<Integer> list = new ArrayList<>();
map.put(root,1);
int Level = 1;
while(queue.size()!=0){
cur = queue.poll();
int NodeLevel = map.get(cur);
if(NodeLevel == Level){
list.add(cur.val);
}else{
Level++;
res.add(new ArrayList(list));
list.clear();
list.add(cur.val);
}
if(cur.left != null){
queue.add(cur.left);
map.put(cur.left,Level+1);
}
if(cur.right != null){
queue.add(cur.right);
map.put(cur.right,Level+1);
}
}
res.add(new ArrayList(list));
return res;
}
}
|