Maximum Depth of Binary Tree

OK, easiest one yet.

Problem: Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.


/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        
        int heightLeft = maxDepth(root.left) + 1;
        int heightRight = maxDepth(root.right) + 1;
        
        return Math.max(heightLeft, heightRight);
    }
}

Advertisements

Balanced Binary Tree

This solution need some house keeping, I think there are tons of other better ways to write it. Especially the returning -99999 part, I don’t like it although it works.

 

 


/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isBalanced(TreeNode root) {
        if (root == null) return true;
        
        int height = recursiveStep(root);
        if (height  1){
            return -99999;
        }
        
        return Math.max(heightLeft, heightRight) + 1;
    }
}

Recursion Solution for Path Sum

Problem: Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

 

 


/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        
        if(root == null) return false;
        
        if(root.val == sum && root.left == null && root.right == null){
            return true;
        }
        
        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
        
    }
}