您的位置:首页 > 其它

二叉树的最大深度与最小深度

2014-10-03 13:39 309 查看
求二叉树的最小深度与最大深度,都是用递归的方法实现。

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

实现代码:

public class Solution {
public int minDepth(TreeNode root) {
if(root == null)
return 0;

int left=minDepth(root.left);
int right=minDepth(root.right);

if(left==0)  //如果左子树为空,则返回右子树深度
return right+1;
if(right==0) //如果右子树为空,则返回左子树深度
return left+1;

return left<right ? left+1:right+1;
}
}


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.

public class Solution {
public int maxDepth(TreeNode root) {
if (root == null)
return 0;
return (Math.max(maxDepth(root.left)+1, maxDepth(root.right)+1));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: