Java: Simple iterative solution using BFS / level order traversal


  • 0
    C

    Simple iterative solution using BFS/level order traversal.

    public int maxDepth(TreeNode root) {
            if (root == null) return 0;
            
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            queue.offer(root);
            
            int count = 0;
            while(!queue.isEmpty()) {
                
                int currentSize = queue.size();    
                //looping thru nodes at the same level
                while (currentSize-- > 0) {
                    
                    TreeNode node = queue.remove();
                    
                    if (node.left != null)
                        queue.offer(node.left);
                    
                    if (node.right != null)
                        queue.offer(node.right);
                }
    
                count++;
            }
            
            return count;
        }
    

Log in to reply
 

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