implementation of transversal of a binary tree javascript code example
Example: 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;
};