My two way Java solutions( dfs with stack and recursion)


  • 1
    
        public int maxDepth(TreeNode root) {
            if(root == null) return 0;
            int max = 0;
            Stack<TreeNode> stack = new Stack<>();
            stack.push(root);
            while(!stack.isEmpty()){
                max++;
                int len = stack.size();
                Stack<TreeNode> temp_stack = new Stack<>();
                for(int i = 0; i < len; i++){
                    TreeNode node = stack.pop();
                    if(node.left != null) temp_stack.push(node.left);
                    if(node.right != null) temp_stack.push(node.right);
                }
                stack.addAll(temp_stack);
            }
            return max;
     }
        //recursion solutin 
       public int maxDepth(TreeNode root) {  
            if(root == null) return 0;
            if(root.left == null && root.right == null){
                return 1;
            }
            return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
        }
        
    
    

  • 1
    S

    in the recursion solution you could remove the second if

    if(root.left == null && root.right == null){
                return 1;
            }
    

    Because you already add 1 level count when you call the function at the end, so it's unnecessary.

    Anyways, hail recursion. :D


Log in to reply
 

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