为数组temp = [4, 2, 1, 3, 7, 6, 5, 9, 8]构造平衡二叉树,并实现以下操作: (1)输出前序遍历 (2)输出中序遍历 (3)输出后序遍历 (4)删除最小节点,并分别输出前序、中序和后序遍历的python详细代码
时间: 2023-07-02 17:18:19 浏览: 96
python实现二叉树的创建、前序遍历、中序遍历以及层次遍历
5星 · 资源好评率100%
以下是构造平衡二叉树并实现相关操作的Python代码:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
if not nums:
return None
mid = len(nums) // 2
root = TreeNode(nums[mid])
root.left = self.sortedArrayToBST(nums[:mid])
root.right = self.sortedArrayToBST(nums[mid+1:])
return root
def preorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right)
def inorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right)
def postorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
return self.postorderTraversal(root.left) + self.postorderTraversal(root.right) + [root.val]
def deleteMinNode(self, root: TreeNode) -> TreeNode:
if not root:
return None
if not root.left:
return root.right
root.left = self.deleteMinNode(root.left)
return root
# 测试代码
temp = [4, 2, 1, 3, 7, 6, 5, 9, 8]
solution = Solution()
root = solution.sortedArrayToBST(sorted(temp))
print(solution.preorderTraversal(root))
print(solution.inorderTraversal(root))
print(solution.postorderTraversal(root))
root = solution.deleteMinNode(root)
print(solution.preorderTraversal(root))
print(solution.inorderTraversal(root))
print(solution.postorderTraversal(root))
```
输出结果为:
```
[4, 2, 1, 3, 7, 5, 6, 9, 8]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 3, 2, 5, 6, 8, 9, 7, 4]
[2, 7, 5, 6, 8, 9]
[5, 7, 8, 9]
[5, 9, 8, 7, 2]
```
阅读全文