一、二叉树的最大深度
题目描述:
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。
代码:
public class Solution {
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
int left=maxDepth(root.left)+1;
int right=maxDepth(root.right)+1;
return Math.max(left,right);
}
}
二、二叉树的最小深度
题目描述:
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.
思路:
递归求解,递归结束的条件是当前节点是空节点,否则需判断其左右子树是否都不为空,都不为空则返回的是左右子树中高度较小的那个值+1,但凡左右子树有一个为空,则返回的较大的那个值+1。
代码:
public class Solution {
public int run(TreeNode root) {
int result=0;
if(root==null){
return result;
}
int depth1=run(root.left)+1;
int depth2=run(root.right)+1;
if(root.left!=null&&root.right!=null){
result=Math.min(depth1,depth2);
}
else{
result=Math.max(depth1,depth2);
}
return result;
}
}