104. Maximum Depth of Binary Tree

来源:互联网 发布:手机多大内存够用 知乎 编辑:程序博客网 时间:2024/05/29 03:13

Given a binary tree, find itsmaximum depth.

The maximum depth is thenumber of nodes along the longest path from the root node down to the farthestleaf node.

    谷歌翻译:给定一个二叉树,找到它的最大深度。最大深度是沿着从根节点到最远叶节点的最长路径的节点数。

    直接利用数据结构中的额递归就可以得出结果,代码如下:

/**

 * Definition for a binary tree node.

 * 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 left=maxDepth(root.left);

        int right=maxDepth(root.right);

        return left>right? left+1:right+1;

    }

}

0 0
原创粉丝点击