Thursday, February 11, 2016

Binary Tree Leaf Sum

Binary Tree Leaf Sum

Given a binary tree, calculate the sum of leaves.

Example
Given
    1
   / \
  2   3
 /
4

return 7.

If a node does not have left child and right child, it is a leaf. We traverse the tree and decide if any node is a leaf. If it is, we add 1 to sum, a private integer which can be accessed in the entire class. 

 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
     * @return an integer
     */
     
    private int sum = 0;
     
    public int leafSum(TreeNode root) {
        // Write your code 
        traverse(root);
        return sum;
        
    }
    
    private void traverse(TreeNode node) {
        if (node == null) {
            return;
        }
        
        if (node.left == null && node.right == null) {
            sum += node.val;
            return;
        }
        
        traverse(node.left);
        traverse(node.right);
        
    }
}