diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index 2229a854..40c65af9 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -468,7 +468,7 @@ class solution: ## go - +### 104.二叉树的最大深度 ```go /** * definition for a binary tree node. @@ -521,6 +521,8 @@ func maxdepth(root *treenode) int { ## javascript +### 104.二叉树的最大深度 + ```javascript var maxdepth = function(root) { if (root === null) return 0; @@ -568,6 +570,8 @@ var maxDepth = function(root) { }; ``` +### 559.n叉树的最大深度 + N叉树的最大深度 递归写法 ```js var maxDepth = function(root) { @@ -600,9 +604,9 @@ var maxDepth = function(root) { }; ``` -## TypeScript: +## TypeScript -> 二叉树的最大深度: +### 104.二叉树的最大深度 ```typescript // 后续遍历(自下而上) @@ -645,7 +649,7 @@ function maxDepth(root: TreeNode | null): number { }; ``` -> N叉树的最大深度 +### 559.n叉树的最大深度 ```typescript // 后续遍历(自下而上) @@ -675,6 +679,8 @@ function maxDepth(root: TreeNode | null): number { ## C +### 104.二叉树的最大深度 + 二叉树最大深度递归 ```c int maxDepth(struct TreeNode* root){ @@ -731,7 +737,8 @@ int maxDepth(struct TreeNode* root){ ## Swift ->二叉树最大深度 +### 104.二叉树的最大深度 + ```swift // 递归 - 后序 func maxDepth1(_ root: TreeNode?) -> Int { @@ -770,7 +777,8 @@ func maxDepth(_ root: TreeNode?) -> Int { } ``` ->N叉树最大深度 +### 559.n叉树的最大深度 + ```swift // 递归 func maxDepth(_ root: Node?) -> Int { @@ -806,5 +814,84 @@ func maxDepth1(_ root: Node?) -> Int { } ``` +## Scala + +### 104.二叉树的最大深度 +递归法: +```scala +object Solution { + def maxDepth(root: TreeNode): Int = { + def process(curNode: TreeNode): Int = { + if (curNode == null) return 0 + // 递归左节点和右节点,返回最大的,最后+1 + math.max(process(curNode.left), process(curNode.right)) + 1 + } + // 调用递归方法,return关键字可以省略 + process(root) + } +} +``` + +迭代法: +```scala +object Solution { + import scala.collection.mutable + def maxDepth(root: TreeNode): Int = { + var depth = 0 + if (root == null) return depth + val queue = mutable.Queue[TreeNode]() + queue.enqueue(root) + while (!queue.isEmpty) { + val len = queue.size + for (i <- 0 until len) { + val curNode = queue.dequeue() + if (curNode.left != null) queue.enqueue(curNode.left) + if (curNode.right != null) queue.enqueue(curNode.right) + } + depth += 1 // 只要有层次就+=1 + } + depth + } +} +``` + +### 559.n叉树的最大深度 + +递归法: +```scala +object Solution { + def maxDepth(root: Node): Int = { + if (root == null) return 0 + var depth = 0 + for (node <- root.children) { + depth = math.max(depth, maxDepth(node)) + } + depth + 1 + } +} +``` + +迭代法: (层序遍历) +```scala +object Solution { + import scala.collection.mutable + def maxDepth(root: Node): Int = { + if (root == null) return 0 + var depth = 0 + val queue = mutable.Queue[Node]() + queue.enqueue(root) + while (!queue.isEmpty) { + val len = queue.size + depth += 1 + for (i <- 0 until len) { + val curNode = queue.dequeue() + for (node <- curNode.children) queue.enqueue(node) + } + } + depth + } +} +``` + -----------------------