您的位置:首页 > 其它

[LeetCode][二叉树]Maximum Depth of Binary Tree

2016-03-21 12:19 330 查看
题目描述:

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.

思路:

前提:二叉树,只包含左右两个子树,最大的深度就是左右两子树的最大深度+1,就是左子树的左右两子树的最大深度+2或右子树的左右两子树的最大深度+2

过程:递归,每次递归只返回当前输入根的最大深度,所以深度初始设置为0,通过递归获取左子树和右子树的深度,选择数值较大的深度+1就是当前输入根的最大深度,初始输入为root根节点即可,递归的终止条件是输入根为null

代码实现:

/**
* 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) {
int depth = 0;
if(root != null){
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
depth++;
if(leftDepth < rightDepth){
depth = depth + rightDepth;
}else{
depth = depth + leftDepth;
}
}
return depth;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: