javascript iterate through a binary tree

Solutions on MaxInterview for javascript iterate through a binary tree by the best coders in the world

showing results for - "javascript iterate through a binary tree"
Pietro
25 Jul 2017
1/**
2 * Definition for a binary tree node.
3 * function TreeNode(val, left, right) {
4 *     this.val = (val===undefined ? 0 : val)
5 *     this.left = (left===undefined ? null : left)
6 *     this.right = (right===undefined ? null : right)
7 * }
8 */
9/**
10 * @param {TreeNode} root
11 * @return {number}
12 */
13var sum = 0;
14
15var traverse = function(item, isLeft){
16    item.left && traverse(item.left, true);
17
18    if (isLeft && item.left == null && item.right == null){
19        sum += item.val;
20    }
21    
22    item.right && traverse(item.right, false);
23}
24
25var sumOfLeftLeaves = function(root) {
26    sum = 0;
27    if (root === null){
28        return 0;
29    }
30    
31    traverse(root, false);
32    
33    return sum;
34};