2.编写非递归遍历代码,实现:给定一棵二叉树的先序遍历序列和中序遍历序列,创建这 棵二叉树。 (1)输出二叉树的后序遍历的结点序列。(2)输出二叉树的叶子结点。(3)统计二叉树的结点个数。(4)求二叉树的深度。 (5)输出二叉树指定结点的路径。
时间: 2024-05-14 07:16:28 浏览: 127
c代码-非递归实现二叉树的创建并先序递归遍历
好的,我会回答你的问题。
以下是非递归遍历二叉树的实现代码:
```python
def create_binary_tree(preorder, inorder):
if not preorder or not inorder:
return None
root = TreeNode(preorder[0])
stack = [root]
i = 0
for char in preorder[1:]:
node = stack[-1]
if node.val != inorder[i]:
node.left = TreeNode(char)
stack.append(node.left)
else:
while stack and stack[-1].val == inorder[i]:
node = stack.pop()
i += 1
node.right = TreeNode(char)
stack.append(node.right)
return root
def postorder_traversal(root):
if not root:
return []
result = []
stack = [(root, False)]
while stack:
node, visited = stack.pop()
if visited:
result.append(node.val)
else:
stack.append((node, True))
if node.right:
stack.append((node.right, False))
if node.left:
stack.append((node.left, False))
return result
def get_leaf_nodes(root):
if not root:
return []
result = []
stack = [root]
while stack:
node = stack.pop()
if not node.left and not node.right:
result.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return result
def count_nodes(root):
if not root:
return 0
stack = [root]
count = 0
while stack:
node = stack.pop()
count += 1
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return count
def get_depth(root):
if not root:
return 0
stack = [(root, 1)]
max_depth = 0
while stack:
node, depth = stack.pop()
if not node.left and not node.right:
max_depth = max(max_depth, depth)
if node.left:
stack.append((node.left, depth + 1))
if node.right:
stack.append((node.right, depth + 1))
return max_depth
def get_path_to_node(root, target):
if not root:
return []
stack = [root]
path = []
while stack:
node = stack.pop()
path.append(node.val)
if node.val == target:
return path
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return []
```
这里的TreeNode表示二叉树的节点,代码中没有给出具体实现,仅用其val属性表示节点的值。以下是一些具体的例子:
```python
preorder = [1, 2, 4, 5, 3, 6, 7]
inorder = [4, 2, 5, 1, 6, 3, 7]
root = create_binary_tree(preorder, inorder)
print(postorder_traversal(root)) # [4, 5, 2, 6, 7, 3, 1]
print(get_leaf_nodes(root)) # [4, 5, 6, 7]
print(count_nodes(root)) # 7
print(get_depth(root)) # 3
print(get_path_to_node(root, 5)) # [1, 2, 5]
```
希望我的回答能够帮到你。
阅读全文