Binary Tree Level Sum(lintcode 482)

Description

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.

Interface

/**
 * 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
     */
    public int levelSum(TreeNode root, int level) {
        // Write your code
    }
}

Solution

/**
 * 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 sum = 0;
        traverse(root, level, 1);
        return sum;
    }

    private void traverse(TreeNode root, int level, int curr) {
        if (root == null) {
            return;
        }

        if (curr == level) {
            sum += root.val;
            return;
        }

        traverse(root.left, level, curr + 1);
        traverse(root.right, level, curr + 1);
    }
}

results matching ""

    No results matching ""