Answers for "javascript iterate through a binary tree"

0

javascript iterate through a binary tree

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var sum = 0;

var traverse = function(item, isLeft){
    item.left && traverse(item.left, true);

    if (isLeft && item.left == null && item.right == null){
        sum += item.val;
    }
    
    item.right && traverse(item.right, false);
}

var sumOfLeftLeaves = function(root) {
    sum = 0;
    if (root === null){
        return 0;
    }
    
    traverse(root, false);
    
    return sum;
};
Posted by: Guest on August-24-2020

Code answers related to "javascript iterate through a binary tree"

Code answers related to "Javascript"

Browse Popular Code Answers by Language