diff --git a/problems/0257.二叉树的所有路径.md b/problems/0257.二叉树的所有路径.md index 6386c48d..e8a98527 100644 --- a/problems/0257.二叉树的所有路径.md +++ b/problems/0257.二叉树的所有路径.md @@ -408,25 +408,57 @@ class Solution { Python: ```Python class Solution: + """二叉树的所有路径 递归法""" + def binaryTreePaths(self, root: TreeNode) -> List[str]: - path=[] - res=[] - def backtrace(root, path): - if not root:return - path.append(root.val) - if (not root.left)and (not root.right): - res.append(path[:]) - ways=[] - if root.left:ways.append(root.left) - if root.right:ways.append(root.right) - for way in ways: - backtrace(way,path) - path.pop() - backtrace(root,path) - return ["->".join(list(map(str,i))) for i in res] + path, result = '', [] + self.traversal(root, path, result) + return result + + def traversal(self, cur: TreeNode, path: List, result: List): + path += str(cur.val) + # 如果当前节点为叶子节点,添加路径到结果中 + if not (cur.left or cur.right): + result.append(path) + return + + if cur.left: + self.traversal(cur.left, path + '->', result) + + if cur.right: + self.traversal(cur.right, path + '->', result) ``` +```python +from collections import deque + + +class Solution: + """二叉树的所有路径 迭代法""" + + def binaryTreePaths(self, root: TreeNode) -> List[str]: + # 题目中节点数至少为1 + stack, path_st, result = deque([root]), deque(), [] + path_st.append(str(root.val)) + + while stack: + cur = stack.pop() + path = path_st.pop() + # 如果当前节点为叶子节点,添加路径到结果中 + if not (cur.left or cur.right): + result.append(path) + if cur.right: + stack.append(cur.right) + path_st.append(path + '->' + str(cur.right.val)) + if cur.left: + stack.append(cur.left) + path_st.append(path + '->' + str(cur.left.val)) + + return result +``` + + Go: ```go func binaryTreePaths(root *TreeNode) []string { diff --git a/problems/0654.最大二叉树.md b/problems/0654.最大二叉树.md index 1a6d39af..b644a0a3 100644 --- a/problems/0654.最大二叉树.md +++ b/problems/0654.最大二叉树.md @@ -258,16 +258,30 @@ class Solution { ## Python ```python -//递归法 class Solution: + """最大二叉树 递归法""" + def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode: - if not nums: return None //终止条件 - root = TreeNode(max(nums)) //新建节点 - p = nums.index(root.val) //找到最大值位置 - if p > 0: //保证有左子树 - root.left = self.constructMaximumBinaryTree(nums[:p]) //递归 - if p < len(nums): //保证有右子树 - root.right = self.constructMaximumBinaryTree(nums[p+1:]) //递归 + return self.traversal(nums, 0, len(nums)) + + def traversal(self, nums: List[int], begin: int, end: int) -> TreeNode: + # 列表长度为0时返回空节点 + if begin == end: + return None + + # 找到最大的值和其对应的下标 + max_index = begin + for i in range(begin, end): + if nums[i] > nums[max_index]: + max_index = i + + # 构建当前节点 + root = TreeNode(nums[max_index]) + + # 递归构建左右子树 + root.left = self.traversal(nums, begin, max_index) + root.right = self.traversal(nums, max_index + 1, end) + return root ```