题目:
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
解法1:递归
/**
* 思路
* 遍历树
* 不断的递归,记录左右节点的深度,返回其中最大的
*/
public int maxDepth(TreeNode root) {
int maxDepth = recursive(root, 1);
return maxDepth;
}
private int recursive(TreeNode root, int maxDepth) {
if (root == null) return maxDepth-1;
int l_max = recursive(root.left, maxDepth + 1);
int r_max = recursive(root.right, maxDepth + 1);
return Math.max(l_max, r_max);
}
时间复杂度:On
空间复杂度:O1
/**
* 思路:
* 获取左右节点中深度最大的那个
* 到了叶子节点0,0返回1
* 递归这个过程
*/
public int maxDepth(TreeNode root) {
if (root==null)return 0;
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return Math.max(leftDepth,rightDepth)+1;
}
时间复杂度:On
空间复杂度:O1
/**
* 思路
* 全局max,记录当前depth
* 比较depth max
*/
int max;
public int maxDepth(TreeNode root) {
recursive(root,1);
return max;
}
private void recursive(TreeNode root, int depth) {
if (root==null)return;
max=depth>max?depth:max;
recursive(root.left,depth+1);
recursive(root.right,depth+1);
}
时间复杂度:On
空间复杂度:O1