Binary Tree Leaf Sum(lintcode 481)
Description
Given a binary tree, calculate the sum of leaves.
Example
Given:
1
/ \
2 3
/
4
return 7.
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
* @return an integer
*/
public int leafSum(TreeNode root) {
// Write your code
}
}
Idea
root == null is absolutely necessary. When a node has only one child and we send another empty child to traverse(), this condition can help the code return.
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
* @return an integer
*/
private int sum = 0;
public int leafSum(TreeNode root) {
// Write your code
traverse(root);
return sum;
}
private void traverse(TreeNode root) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
sum += root.val;
return;
}
traverse(root.left);
traverse(root.right);
}
}