From c44a3165c4333530eac041aa1ede69088ed6462c Mon Sep 17 00:00:00 2001 From: Baturu <45113401+z80160280@users.noreply.github.com> Date: Fri, 4 Jun 2021 03:08:41 -0700 Subject: [PATCH] =?UTF-8?q?Update=200104.=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E6=9C=80=E5=A4=A7=E6=B7=B1=E5=BA=A6.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0104.二叉树的最大深度.md | 105 ++++++++++++++++++++++ 1 file changed, 105 insertions(+) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index 756afb68..4bf2b261 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -281,6 +281,111 @@ class Solution { Python: +104.二叉树的最大深度 +> 递归法: +```python +class Solution: + def maxDepth(self, root: TreeNode) -> int: + return self.getDepth(root) + + def getDepth(self, node): + if not node: + return 0 + leftDepth = self.getDepth(node.left) #左 + rightDepth = self.getDepth(node.right) #右 + depth = 1 + max(leftDepth, rightDepth) #中 + return depth +``` +> 递归法;精简代码 +```python +class Solution: + def maxDepth(self, root: TreeNode) -> int: + if not root: + return 0 + return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) +``` + +> 迭代法: +```python +import collections +class Solution: + def maxDepth(self, root: TreeNode) -> int: + if not root: + return 0 + depth = 0 #记录深度 + queue = collections.deque() + queue.append(root) + while queue: + size = len(queue) + depth += 1 + for i in range(size): + node = queue.popleft() + if node.left: + queue.append(node.left) + if node.right: + queue.append(node.right) + return depth +``` + +559.N叉树的最大深度 +> 递归法: +```python +class Solution: + def maxDepth(self, root: 'Node') -> int: + if not root: + return 0 + depth = 0 + for i in range(len(root.children)): + depth = max(depth, self.maxDepth(root.children[i])) + return depth + 1 +``` + +> 迭代法: +```python +import collections +class Solution: + def maxDepth(self, root: 'Node') -> int: + queue = collections.deque() + if root: + queue.append(root) + depth = 0 #记录深度 + while queue: + size = len(queue) + depth += 1 + for i in range(size): + node = queue.popleft() + for j in range(len(node.children)): + if node.children[j]: + queue.append(node.children[j]) + return depth +``` + +> 使用栈来模拟后序遍历依然可以 +```python +class Solution: + def maxDepth(self, root: 'Node') -> int: + st = [] + if root: + st.append(root) + depth = 0 + result = 0 + while st: + node = st.pop() + if node != None: + st.append(node) #中 + st.append(None) + depth += 1 + for i in range(len(node.children)): #处理孩子 + if node.children[i]: + st.append(node.children[i]) + + else: + node = st.pop() + depth -= 1 + result = max(result, depth) + return result +``` + Go: