题解 | #二叉树的深度#
二叉树的深度
https://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b
import java.util.*; /** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { //递归 public int TreeDepth(TreeNode root) { if(root == null){ return 0; } //求最大深度=求根的高度 ,求高度用后序遍历 左右根 int leftHeight = 1 + TreeDepth(root.left);//左 int rightHeight = 1 + TreeDepth(root.right);//右 int maxHeight = Math.max(leftHeight,rightHeight);//中 return maxHeight; //简化 //return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; //更简化 //return root == null?0:Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; } }