/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */// dfsclassSolution {publicintmaxDepth(TreeNode root) {if(root ==null)return0;returnMath.max(maxDepth(root.left),maxDepth(root.right)) +1; }}
3.2 Kotlin
/** * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */classSolution {funmaxDepth(root: TreeNode?): Int {returnif (root ==null) 0else Math.max(maxDepth(root.left), maxDepth(root.right)) +1 }}
3.3 复杂度分析
时间复杂度 O(N) :N 为树的结点数量,计算树的深度需要遍历到所有的结点。
空间复杂度 O(N) :最差情况下,当树退化为链表,递归的深度会达到 N。
4. 解法 - BFS
4.1 Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */// bfsclassSolution {publicintmaxDepth(TreeNode root) {// 判空if (root ==null)return0;// 使用队列存储节点Queue<TreeNode> queue =newLinkedList<>();// 初始化,先令根节点入队queue.offer(root);// 二叉树深度,最后要返回的结果int depth =0;while (!queue.isEmpty()) {// 当前层次的节点数目int curSize =queue.size();// 遍历当前层次的所有节点,并将他们的子节点都入队int i =0;while (i < curSize) {TreeNode curNode =queue.poll();// 左右子树存在的话就将其入队if (curNode.left!=null)queue.offer(curNode.left);if (curNode.right!=null)queue.offer(curNode.right); i++; }// 遍历完一个层次,就将深度++ depth++; }return depth; }}
4.2 Kotlin
/** * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */classSolution {funmaxDepth(root: TreeNode?): Int {// 判空if (root ==null)return0// 使用队列存储节点val queue =LinkedList<TreeNode>()// 初始化,先令根节点入队 queue.offer(root)// 二叉树深度,最后要返回的结果var depth =0while (!queue.isEmpty()) {// 当前层次的节点数目val curSize = queue.size// 遍历当前层次的所有节点,并将他们的子节点都入队var i =0while (i < curSize) {val curNode = queue.poll()// 左右子树存在的话就将其入队if (curNode.left !=null) queue.offer(curNode.left)if (curNode.right !=null) queue.offer(curNode.right) i++ }// 遍历完一个层次,就将深度++ depth++ }return depth }}