4ms Java Solution


  • 0
    P
    public class Solution {
          public static List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> result = new LinkedList<List<Integer>>();
            List<TreeNode>queue = new ArrayList<TreeNode>();
            if(root==null)return result;
            int k = 2;
            List<Integer> list = new LinkedList<Integer>();
            list.add(root.val);
            queue.add(root.left);
            queue.add(root.right);
            result.add(list);
            while(queue.size()>0){
                List<Integer> list2 = new LinkedList<Integer>();
                int j = k;  k = 0;
                for(int i = 0;i<j;i++){
                	if(queue.size()==0)break;
                    TreeNode node = queue.get(0);queue.remove(0);
                    if(node!=null){
                        list2.add(node.val);
                        queue.add(node.left);k++;
                        queue.add(node.right);k++;
                    }
                }
                if(list2.size()!=0)result.add(list2);
            }
          return result;  
        }
        
    }

Log in to reply
 

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