http://www.lintcode.com/en/problem/maximum-depth-of-binary-tree/ https://leetcode.com/problems/maximum-depth-of-binary-tree/description/

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.

Example Given a binary tree as follow:

   1
  / \ 
 2   3
    / \
   4   5

The maximum depth is 3.

解题:这题要求二叉树最大的深度,用一个max变量跟着遍历一遍,把max作为返回值就好了。

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

    public int maxDepthHelper(TreeNode node, int max) {
        if(node.left == null && node.right == null) {
            return max;
        }
        int left = 0, right = 0;
        if(node.left != null) {
             left = maxDepthHelper(node.left, max+1);
        }
        if(node.right != null) {
             right = maxDepthHelper(node.right, max+1);
        }

        if(left > right) {
            return left;
        }else {
            return right;
        }       
    }
}

results matching ""

    No results matching ""