给定一棵二叉树,使用非递归的方式实现二叉树左右子树交换,并输出后序遍历结果,要求完善以下代码
时间: 2024-05-11 17:19:29 浏览: 77
c代码-非递归实现二叉树的创建并先序递归遍历
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def postorderTraversal(root):
if not root:
return []
stack = []
output = []
stack.append(root)
while stack:
current_node = stack.pop()
output.append(current_node.val)
if current_node.left:
stack.append(current_node.left)
if current_node.right:
stack.append(current_node.right)
return output[::-1]
def invertTree(root):
if not root:
return None
stack = []
stack.append(root)
while stack:
current_node = stack.pop()
temp = current_node.left
current_node.left = current_node.right
current_node.right = temp
if current_node.left:
stack.append(current_node.left)
if current_node.right:
stack.append(current_node.right)
return root
# 测试代码
root = TreeNode(4)
root.left = TreeNode(2)
root.right = TreeNode(7)
root.left.left = TreeNode(1)
root.left.right = TreeNode(3)
root.right.left = TreeNode(6)
root.right.right = TreeNode(9)
print("原二叉树后序遍历结果:", postorderTraversal(root))
invertTree(root)
print("翻转后二叉树后序遍历结果:", postorderTraversal(root))
```
运行结果:
```
原二叉树后序遍历结果: [1, 3, 2, 6, 9, 7, 4]
翻转后二叉树后序遍历结果: [9, 6, 7, 3, 1, 2, 4]
```
阅读全文