[Java] DFS Recursion Solution


  • 0
    C

    This is my first submission and success without using discussion posts for help. It uses Depth First Search recursion hitting each node. It keeps track of the node's depth as we go and if it surpasses the max depth recorded, it will set depth = to the nodes level.

    //set our global max depth value
    public int depth = 0;
    
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        else depth = 1;
        
        //call Depth First Search with a starting level of 1 - level will keep track of the nodes depth
        DFS(root,1);
        
        // return our global depth value
        return depth;
    }
    
    public void DFS(TreeNode root, int level){
        //This shouldn't be hit but just in case we will return if the node is null
        if(root == null) return;
        
        //if the nodes depth is > global depth, set global depth = nodes depth
        if(level > depth) depth = level;
        
        if(root.left != null){
            //Go down the left side of tree, increase the node's level to keep track of what depth it is
            DFS(root.left,level+1);
        }
        
        //hit the right nodes if they exist, keeping track of node level
        if(root.right!= null) DFS(root.right,level+1);
    }

  • 3
    E

    I think your code is a bit of complicated, try mine, it has the same theory but more concise.

    public int maxDepth(TreeNode root) {

        if (root==null)
            return 0;
        else
            return Math.max(maxDepth(root.left), maxDepth(root.right))+1;
    
    }

  • 0
    C

    This makes a lot of sense to do it this way and it is very concise!


Log in to reply
 

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