Java bfs with private class


  • 0
    C
    public class Solution {
        Map<Integer, List<Integer>> dict=new TreeMap<>();
        public List<List<Integer>> verticalOrder(TreeNode root) {
            List<List<Integer>> res=new ArrayList<>();
            bfs(root);
            res.addAll(dict.values());
            return res;
        }
        
        private void bfs(TreeNode root){
            Queue<LevelNode> que=new LinkedList<>();
            que.add(new LevelNode(root,0));
            while(!que.isEmpty()){
                LevelNode parent=que.poll();
                if(parent.node==null) continue;
                List<Integer> list=dict.getOrDefault(parent.level,new ArrayList<>());
                list.add(parent.node.val);
                dict.put(parent.level,list);
                
                que.add(new LevelNode(parent.node.left,parent.level-1));
                que.add(new LevelNode(parent.node.right,parent.level+1));
            }
        }
        
        private class LevelNode{
            TreeNode node;
            int level;
            
            public LevelNode(TreeNode node,int level){
                this.node=node;
                this.level=level;
            }
            
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.