题目描述

题解
// 这道题跟【剑指offer】55. 二叉树的深度 一模一样。
// 前序遍历
// 前序遍历,deep记录当前深度,max记录deep中的最大深度。
// 往左右子树走deep+1,返回父结点deep-1。最后返回max
// 执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
// 内存消耗:38.5 MB, 在所有 Java 提交中击败了49.78%的用户
class Solution {
int max = 0
int deep = 0
public int maxDepth(TreeNode root) {
if (root == null)
return max
this.max = 1
this.deep = 1
preOrder(root)
return max
}
private void preOrder(TreeNode root) {
if (root == null) {
return
}
if (root.left != null) {
max = Math.max(++deep, max)
preOrder(root.left)
deep--
}
if (root.right != null) {
max = Math.max(++deep, max)
preOrder(root.right)
deep--
}
}
}
class Solution {
public int maxDepth(TreeNode root) {
if (root == null)
return 0;
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return (left > right) ? left + 1 : right + 1;
}
}
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left, right) + 1;
}
}