以二叉链表建立二叉树链式存储结构,实现前序遍历、求叶子结点的个数计算、中序遍历、后序遍历、求深度。画出其流程图
时间: 2024-01-29 22:04:40 浏览: 106
层次序遍历-二叉树的存储结构和遍历算法
好的,我会为你调用ChitGPT来回答这个问题。以下是其代码实现和流程图:
```python
#定义二叉树结点
class TreeNode:
def __init__(self, value):
self.val = value
self.left = None
self.right = None
#二叉树类
class BinaryTree:
def __init__(self, data):
self.root = TreeNode(data)
#前序遍历
def preorderTraversal(self, root):
if root is None:
return []
res = [root.val]
res += self.preorderTraversal(root.left)
res += self.preorderTraversal(root.right)
return res
#求叶子结点的个数
def countLeaves(self, root):
if root is None:
return 0
elif root.left is None and root.right is None:
return 1
else:
return self.countLeaves(root.left) + self.countLeaves(root.right)
#中序遍历
def inorderTraversal(self, root):
if root is None:
return []
res = []
res += self.inorderTraversal(root.left)
res += [root.val]
res += self.inorderTraversal(root.right)
return res
#后序遍历
def postorderTraversal(self, root):
if root is None:
return []
res = []
res += self.postorderTraversal(root.left)
res += self.postorderTraversal(root.right)
res += [root.val]
return res
#求深度
def maxDepth(self, root):
if root is None:
return 0
else:
left_depth = self.maxDepth(root.left)
right_depth = self.maxDepth(root.right)
return max(left_depth, right_depth) + 1
#建立二叉链表
# 1
# / \
# 2 3
# / \ \
# 4 5 6
root = TreeNode(1)
root.left = TreeNode(2)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right = TreeNode(3)
root.right.right = TreeNode(6)
#测试
bt = BinaryTree(1)
print(f"前序遍历:{bt.preorderTraversal(root)}")
print(f"叶子结点个数:{bt.countLeaves(root)}")
print(f"中序遍历:{bt.inorderTraversal(root)}")
print(f"后序遍历:{bt.postorderTraversal(root)}")
print(f"深度:{bt.maxDepth(root)}")
```
流程图如下:
![BinaryTree](https://img-blog.csdn.net/20180725203301705?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvamlhbnlpMjAxNzA2/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/q/70)
阅读全文