Simple Java Recursion and Iterative with Stack Solutions


  • 0

    Recursive

    public int sumOfLeftLeaves(TreeNode root) {
    	int sum = 0;
    	if(root==null) 
    		return sum;
    	if(root.left!=null && root.left.left==null && root.left.right==null) {
    		sum += root.left.val;
    	}
    	sum+=sumOfLeftLeaves(root.left);
    	sum+=sumOfLeftLeaves(root.right);
    	return sum;
    }
    

    Iterative with Stack

    public int sumOfLeftLeaves(TreeNode root) {
    	if(root==null) return 0;
    	int sum = 0;
    	Deque<TreeNode> stack = new ArrayDeque<>();
    	stack.push(root);
    	while(!stack.isEmpty()) {
    		TreeNode current = stack.pop();
    		if(current.left!=null) {
    			if(current.left.left==null && current.left.right==null) sum+=current.left.val;
    			 stack.push(current.left);
    		}
    		if(current.right!=null) stack.push(current.right);
    	}
    	return sum;
    }
    

Log in to reply
 

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