二叉树的深度 I
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
给定二叉树 [3,9,20,null,null,15,7],
3 / \ 9 20 / \ 15 7
返回它的最大深度 3 。
题解
-
dfs (看看大佬的解法)
- 算法思想
- 深度优先搜索,每遍历一层自增 1,记录下最大深度
- 复杂度分析
- 时间复杂度 O(n)
- 空间复杂度 O(n):当二叉树退化为链表的时候需要 O(n)的栈空间
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { int res; public int maxDepth(TreeNode root) { dfs(root,0); return res; } void dfs(TreeNode root,int depth){ if(root == null)return; if(++depth > res)res = depth; dfs(root.left,depth); dfs(root.right,depth); } }
大佬写法
class Solution { public int maxDepth(TreeNode ro
- 算法思想