给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree
1 public class MaximumDepthofBinaryTree {
2 public class TreeNode {
3 int val;
4 TreeNode left;
5 TreeNode right;
6 TreeNode(int x) {
7 val = x;
8 }
9 }
10 //方法一:递归 从root节点开始,比较的是左子树和右子树的高度,以左结点为一棵树,也是比较其左子树和右子树的高度,以此类推
11 public int maxDepth(TreeNode root) {
12 if(root == null) {
13 return 0;
14 }
15 int left = maxDepth(root.left);
16 int right = maxDepth(root.right);
17 return Math.max(left, right) + 1;
18 }
19 }
来源:https://www.cnblogs.com/xiyangchen/p/11065000.html