Java Recursive Solution with Helper Function


  • 0
    A

    Find the maximum depth of the tree and the find the leftmost bottom value recursively.

    public class Solution {
        private int res;
        private boolean flag;
        public int findBottomLeftValue(TreeNode root) {
            int depth = FindDepth(root);
            getBottomLeft(root,1,depth);
            return res;
        }
        
        private void getBottomLeft(TreeNode node, int dep, int maxdepth){
      
            if(node == null)
                return;
            if(dep == maxdepth && node.left == null && node.right == null && !flag){
                res = node.val;
                flag = true;
                return;
            }
                
            getBottomLeft(node.left, dep+1, maxdepth);    
            getBottomLeft(node.right,dep+1,maxdepth); 
            return;
        }
    
        private int FindDepth(TreeNode root){
            if(root == null)
                return 0;
            return 1 + Math.max(FindDepth(root.left),FindDepth(root.right));     
        }
    }
    

Log in to reply
 

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