建立二叉树的二叉链表非递归中序遍历
时间: 2023-12-23 12:28:04 浏览: 89
以下是建立二叉树的二叉链表非递归中序遍历的示例代码:
```python
class BiTreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def create_binary_tree():
# 创建二叉树
# 这里只是一个示例,实际情况下可以根据具体需求进行修改
root = BiTreeNode(1)
node2 = BiTreeNode(2)
node3 = BiTreeNode(3)
node4 = BiTreeNode(4)
node5 = BiTreeNode(5)
node6 = BiTreeNode(6)
node7 = BiTreeNode(7)
root.left = node2
root.right = node3
node2.left = node4
node2.right = node5
node3.left = node6
node3.right = node7
return root
def inorder_traversal(root):
# 非递归中序遍历二叉树
stack = []
node = root
while node or stack:
while node:
stack.append(node)
node = node.left
if stack:
node = stack.pop()
print(node.data, end=" ")
node = node.right
# 创建二叉树
root = create_binary_tree()
# 非递归中序遍历二叉树
inorder_traversal(root)
```
输出结果为:4 2 5 1 6 3 7
阅读全文