Swift, C++, dfs iterate


  • 0
    X

    iterate the entire tree, when we find a left leave then sum+=parent.left.val;

    // Swift
    class Solution {
        func sumOfLeftLeaves(_ root: TreeNode?) -> Int {
            if root==nil || (root?.left==nil && root?.right==nil) {
                return 0
            }
            var sum:Int = 0
            findLeftLeaves(root, &sum)
            return sum
        }
        private func findLeftLeaves(_ rt: TreeNode?, _ sum:inout Int){
            guard let r = rt else { return }
            if isLeave(r.left) {
                sum += r.left!.val
            }
            findLeftLeaves(r.left,  &sum)
            findLeftLeaves(r.right, &sum)
        }
        private func isLeave(_ rt: TreeNode?) -> Bool {
            guard let r = rt else { return false }
            if r.left==nil, r.right==nil {
                return true
            }
            return false
        }
    }
    
    // C++
    class Solution {
    public:
        int sumOfLeftLeaves(TreeNode* root) {
            if(!root || (!root->left && !root->right)) return 0;
            int sum = 0; 
            findLeaves(root, sum); 
            return sum;
        }
        void findLeaves(TreeNode* r, int &sum){
            if(!r) return;
            if(r->left && !r->left->left && !r->left->right) sum += r->left->val;
            findLeaves(r->left,  sum); 
            findLeaves(r->right, sum);
        }
    };
    

Log in to reply
 

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