中级农民
- 积分
- 108
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-2-26
- 最后登录
- 1970-1-1
|
多谢您的回复!利用节点的out-degree,确实可以。不过这样的话,相当于遍历2遍,对吧。以下是我写的代码,主要是用两个hashmap分别存每个节点的children,以及它的parent。麻烦您帮忙看一下,还有可以优化的地方吗?这个bfs的运行时间是dfs的2倍呢,:( 非常感谢!
public List<List<Integer>> findLeaves(TreeNode root) {
List<List<Integer>> res=new ArrayList<>();
if(root==null) return res;
HashMap<TreeNode,List<TreeNode>> children=new HashMap<>();
HashMap<TreeNode,TreeNode> parent=new HashMap<>();
Queue<TreeNode> queue=new LinkedList<>();queue.offer(root);
//get the parent-children relation
while(!queue.isEmpty()){
TreeNode cur=queue.poll();
if(!children.containsKey(cur)) children.put(cur,new ArrayList<>());
if(cur.left!=null){
children.get(cur).add(cur.left);parent.put(cur.left,cur);queue.offer(cur.left);
}
if(cur.right!=null){
children.get(cur).add(cur.right);parent.put(cur.right,cur);queue.offer(cur.right);
}
}
//topological sort
for(TreeNode cur:children.keySet()){
if(children.get(cur).isEmpty()) {queue.offer(cur);}
}
while(!queue.isEmpty()){
int size=queue.size();List<Integer> tmp=new ArrayList<>();
for(int i=0;i<size;i++){
TreeNode cur=queue.poll();tmp.add(cur.val);
TreeNode pa=parent.get(cur);
if(pa!=null) {
children.get(parent.get(cur)).remove(cur);
if(children.get(pa).isEmpty())
queue.offer(pa);
}
}
res.add(tmp);
}
return res;
} |
|