Solution Tempelate


  • 0
    U

    For Binary tree Zig Zag:

        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> res = new LinkedList<>();
            if(root==null) return res;
            Queue<TreeNode> q=new LinkedList<>();
            
            q.offer(root);
            int level=0;
            while(!q.isEmpty()){
                level=level+1;
                int len=q.size();
                List<Integer> temp = new ArrayList<>();
                for(int i=0;i<len;i++){
                    TreeNode n=q.poll();
                    if(n.left!=null) q.offer(n.left);
                    if(n.right!=null)q.offer(n.right);
                    temp.add(n.val);
                }
                if(level%2==0) Collections.reverse(temp);
                res.add(temp);
            }
            return res;
        }
    }
    
    
    102. Binary tree Level Order
    ```  public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> res = new ArrayList<>();
            if (root == null) return res;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.add(root);
            while(!queue.isEmpty()){
                List<Integer> level = new ArrayList<>();
                int cnt =queue.size();
                for(int i=0;i<cnt;i++){
                TreeNode node = queue.poll();
                level.add(node.val);
                if(node.left!=null) queue.add(node.left);
                if(node.right!=null) queue.add(node.right);
                }
                res.add(level);
            }
            return res;
            
        }
    
    
    116. Populating next pointer 
    
    public void connect(TreeLinkNode root) {
                if (root ==null || root.left==null && root.right==null) return;
            Queue<TreeLinkNode> q = new LinkedList<>();
            q.offer(root);
            
            while(!q.isEmpty()){
                int size = q.size();
                for(int i=0;i<size;i++){
                    TreeLinkNode t = q.poll();
                    
                    if(q.peek()==null ||i==size-1 )t.next=null;
                    else {
                        t.next=q.peek();
                    }
                    
                    if(t.left!=null)q.offer(t.left);
                    if(t.right!=null)q.offer(t.right);
                }
            }

Log in to reply
 

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