Java Solution With Queue


  • 0
    C
    public class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            
            if (root == null) {
    			return 0;
    		}
    
    		Queue<TreeNode> queue = new LinkedList<>();
    		queue.add(root);
    		int sum = 0;
    
    		while (!queue.isEmpty()) {
    			TreeNode top = queue.poll();
    			if (top.left != null) {
    				queue.add(top.left);
    				if (top.left.left == null && top.left.right == null) {
    					sum += top.left.val;
    				}
    			}
    			if (top.right != null) {
    				queue.add(top.right);
    			}
    		}
    
    		return sum;
    	}
    }
    

Log in to reply
 

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