104. Maximum Depth of Binary Tree
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.这里先使用递归的方法,递归终止条件:传入的root为空
依次求左右深度,递归root的左右子树
最后return 左右深度最大的那个+1
代码:
package easy;
public class MaximumDepthofBinaryTree {
public int maxDepth(TreeNode root) {
if(null == root){
return 0;
}
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return leftDepth > rightDepth ? leftDepth+1 : rightDepth+1;
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}