Thursday, February 11, 2016

Binary Tree Level Sum

Binary Tree Level Sum

Given a binary tree and an integer which is the depth of the target level.
Calculate the sum of the nodes in the target level.

Example
Given a binary tree:
     1
   /   \
  2     3
 / \   / \
4   5 6   7
   /       \
  8         9
For depth = 2, return 5.
For depth = 3, return 22.
For depth = 4, return 17.

We use depth to keep track of the target level. If it equals to the target level, add node.val to sum, and stop traversing the node's children.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root the root of the binary tree
     * @param level the depth of the target level
     * @return an integer
     */
     
    private int sum = 0;
    
    public int levelSum(TreeNode root, int level) {
        // Write your code
        int depth = 1;
        traverse(root, depth, level);
        return sum;
    }
    
    private void traverse(TreeNode node, int depth, int level) {
        if (node == null) {
            return;
        }
        
        if (depth == level) {
            sum += node.val;
            return;
        }
        
        traverse(node.left, depth + 1, level);
        traverse(node.right, depth + 1, level);
        
    }
}