Java iterative solution


  • 2
    W
    public int maxDepth(TreeNode root) {
        if(root==null) return 0; 
        int count = 0; 
        Queue<TreeNode> q = new LinkedList<TreeNode>(); 
        q.offer(root); 
        while(!q.isEmpty()){
            int levelNum = q.size(); 
            count++; 
            for(int i=0; i<levelNum; i++){
                TreeNode node = q.poll(); 
                if(node.left!=null) q.offer(node.left); 
                if(node.right!=null) q.offer(node.right); 
            }
        }
        return count; 
    }

Log in to reply
 

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