Maximum Depth of Binary Tree

题目

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.

 

 

题解:

与minimum代码几乎完全一样,只需要修改math.min为math.max

public class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return getMin(root);
    }

    public int getMin(TreeNode root){
        if (root == null) {
            return Integer.MIN_VALUE;
        }

        if (root.left == null && root.right == null) {
            return 1;
        }

        return Math.max(getMin(root.left), getMin(root.right)) + 1;
    }
}

 

 用divide and conquer

public class Solution {
    public int maxDepth(TreeNode root) 
    {
        if (root==null) return 0;
        int left=maxDepth(root.left);
        int right=maxDepth(root.right);
        return Math.max(left,right)+1;
        
    }
}

 

posted @ 2015-08-05 06:33  Hygeia  阅读(146)  评论(0编辑  收藏  举报