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: