您的位置:首页 > 其它

LeetCode 104. Maximum Depth of Binary Tree

2016-02-11 16:34 411 查看
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.

本题目是简单的二叉树深度问题,二叉树是每个节点最多有两个子树的树结构,二叉树还有递归定义:

二叉树是n(n>=0)个有限结点构成的集合。N=0称为空二叉树;n>0的二叉树由一个根结点和两互不相交的,分别称为左子树和右子树的二叉树构成。

二叉树中任何结点的第1个子树称为其左子树,左子树的根称为该结点的左孩子;二叉树中任何结点的第2个子树称为其右子树,左子树的根称为该结点的右孩子。

更多二叉树的性质和实现:见luoweifu的博客 二叉树(1)——二叉树的定义和递归实现

利用递归求二叉树的最大深度:

/**
* 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 leftMaxDepth = maxDepth(root.left);
int rightMaxDepth = maxDepth(root.right);
return 1 + Math.max(leftMaxDepth,rightMaxDepth);
}
}


简单解释:将每个结点都看做根节点,如果结点为空,则返回0,此为递归的出口,如果不为空,则深度至少为1,分别求其左子树和右子树的深度,进行比较,即可求出最大深度。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: