Java with BFS


  • 0
    E
    public int maxDepth(TreeNode root) {
            int level=0;
            if(root!=null){
                Queue<TreeNode> queue=new LinkedList<>();
                queue.offer(root);
                while(!queue.isEmpty()){
                    int levelSize=queue.size();
                    while(levelSize>0){
                        TreeNode node=queue.poll();
                        if(node.left!=null) queue.offer(node.left);
                        if(node.right!=null) queue.offer(node.right);
                        levelSize--;
                    }
                    level++;
                }
            }
            return level;
        }
    

Log in to reply
 

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