(1) 二叉树的相关操作演示。 自定义结点结构,以二叉链表为存储结构,完成以下功能: 1) 以先序递归方式创建一棵二叉树; 2) 输出二叉树的先序、中序和后序递归或非递归遍历下的结点访问次序; 3) 输出二叉树所有的叶子节点和叶子节点个数; 4) 输出二叉树的高度; 5) 输出二叉树的按层次遍历序列
时间: 2024-02-12 09:05:46 浏览: 103
好的,下面是对应的代码实现:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root = None
# 创建二叉树
def createTree(self):
val = input("请输入结点的值,输入#表示空节点:")
if val == '#':
return None
node = TreeNode(int(val))
node.left = self.createTree()
node.right = self.createTree()
return node
# 先序遍历(递归)
def preOrderRecursion(self, root):
if not root:
return
print(root.val, end=' ')
self.preOrderRecursion(root.left)
self.preOrderRecursion(root.right)
# 中序遍历(递归)
def inOrderRecursion(self, root):
if not root:
return
self.inOrderRecursion(root.left)
print(root.val, end=' ')
self.inOrderRecursion(root.right)
# 后序遍历(递归)
def postOrderRecursion(self, root):
if not root:
return
self.postOrderRecursion(root.left)
self.postOrderRecursion(root.right)
print(root.val, end=' ')
# 先序遍历(非递归)
def preOrder(self, root):
if not root:
return
stack = [root]
while stack:
node = stack.pop()
print(node.val, end=' ')
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
# 中序遍历(非递归)
def inOrder(self, root):
if not root:
return
stack = []
node = root
while node or stack:
while node:
stack.append(node)
node = node.left
node = stack.pop()
print(node.val, end=' ')
node = node.right
# 后序遍历(非递归)
def postOrder(self, root):
if not root:
return
stack1 = [root]
stack2 = []
while stack1:
node = stack1.pop()
if node.left:
stack1.append(node.left)
if node.right:
stack1.append(node.right)
stack2.append(node)
while stack2:
print(stack2.pop().val, end=' ')
# 获取叶子节点和叶子节点个数
def getLeaves(self, root):
if not root:
return []
leaves = []
stack = [root]
while stack:
node = stack.pop()
if not node.left and not node.right:
leaves.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return leaves, len(leaves)
# 获取二叉树的高度
def getHeight(self, root):
if not root:
return 0
left_height = self.getHeight(root.left)
right_height = self.getHeight(root.right)
return max(left_height, right_height) + 1
# 按层次遍历
def levelOrder(self, root):
if not root:
return []
level = [root]
res = []
while level:
res.append([node.val for node in level])
temp = []
for node in level:
if node.left:
temp.append(node.left)
if node.right:
temp.append(node.right)
level = temp
return res
```
可以使用下面的代码进行测试:
```python
if __name__ == '__main__':
bt = BinaryTree()
bt.root = bt.createTree()
print("先序遍历(递归):")
bt.preOrderRecursion(bt.root)
print("\n中序遍历(递归):")
bt.inOrderRecursion(bt.root)
print("\n后序遍历(递归):")
bt.postOrderRecursion(bt.root)
print("\n先序遍历(非递归):")
bt.preOrder(bt.root)
print("\n中序遍历(非递归):")
bt.inOrder(bt.root)
print("\n后序遍历(非递归):")
bt.postOrder(bt.root)
print("\n叶子节点和叶子节点个数:")
print(bt.getLeaves(bt.root))
print("二叉树的高度:")
print(bt.getHeight(bt.root))
print("按层次遍历:")
print(bt.levelOrder(bt.root))
```
希望能够帮助到您!
阅读全文