Recursive and BFS elegant Solution


  • 0

    Recursive version

    public class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            if(root == null || isLeaf(root)) return 0;
            return sumOfLeft(root);
        }
    
        public int sumOfLeft(TreeNode root) {
            if(root == null) return 0;
            if(isLeaf(root)) return root.val;
    
            int left = sumOfLeft(root.left);
            int right = sumOfLeft(root.right);
            return isLeaf(root.right) ? left : left + right;
        }
    
        private boolean isLeaf(TreeNode root){
            if(root == null) return false;
            return root.left == null && root.right == null;
        }
    }
    

    BFS version:

    public class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            if(root == null || isLeaf(root)) return 0;
    
            int sum = 0;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
    
            while(!queue.isEmpty()){//if cur.left == null , do nothing
                TreeNode cur = queue.poll();
                if(cur.left != null){
                    if(isLeaf(cur.left)){
                        sum += cur.left.val;
                    }else{
                        queue.offer(cur.left);
                    }
                }
    
                if(cur.right != null){//if cur.right == null , do nothing
                    if(isLeaf(cur.right)){
                        continue;//do nothing
                    }else{
                        queue.offer(cur.right);
                    }
                }
            }
            return sum;
        }
    
        private boolean isLeaf(TreeNode root){
            if(root == null) return false;
            return root.left == null && root.right == null;
        }
    }
    

Log in to reply
 

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