完成二叉树二叉链表结构的定义 ,实现二叉链表的创建,先序、中序和后序遍历算法的实现。,实现二叉树求结点个数,求高度,求叶子结点数、交换二叉树左右子树的算法的完整代码
时间: 2023-12-10 17:37:09 浏览: 78
编写采用二叉链表形式存储的二叉树的创建、先序、中序、后序和按层遍历的算法
5星 · 资源好评率100%
二叉树二叉链表结构的定义:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
```
二叉链表的创建:
```python
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
if not inorder or not postorder:
return None
root_val = postorder[-1]
root = TreeNode(root_val)
mid = inorder.index(root_val)
left_inorder = inorder[:mid]
right_inorder = inorder[mid+1:]
left_postorder = postorder[:mid]
right_postorder = postorder[mid:-1]
root.left = self.buildTree(left_inorder, left_postorder)
root.right = self.buildTree(right_inorder, right_postorder)
return root
```
先序遍历:
```python
def preorderTraversal(self, root: TreeNode) -> List[int]:
res = []
def dfs(node):
if not node:
return
res.append(node.val)
dfs(node.left)
dfs(node.right)
dfs(root)
return res
```
中序遍历:
```python
def inorderTraversal(self, root: TreeNode) -> List[int]:
res = []
def dfs(node):
if not node:
return
dfs(node.left)
res.append(node.val)
dfs(node.right)
dfs(root)
return res
```
后序遍历:
```python
def postorderTraversal(self, root: TreeNode) -> List[int]:
res = []
def dfs(node):
if not node:
return
dfs(node.left)
dfs(node.right)
res.append(node.val)
dfs(root)
return res
```
求结点个数:
```python
def countNodes(self, root: TreeNode) -> int:
if not root:
return 0
return 1 + self.countNodes(root.left) + self.countNodes(root.right)
```
求高度:
```python
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
left_depth = self.maxDepth(root.left)
right_depth = self.maxDepth(root.right)
return max(left_depth, right_depth) + 1
```
求叶子结点数:
```python
def countLeaves(self, root: TreeNode) -> int:
if not root:
return 0
if not root.left and not root.right:
return 1
return self.countLeaves(root.left) + self.countLeaves(root.right)
```
交换二叉树左右子树:
```python
def invertTree(self, root: TreeNode) -> TreeNode:
if not root:
return None
left = root.left
right = root.right
root.left = self.invertTree(right)
root.right = self.invertTree(left)
return root
```
阅读全文