本关任务:给定一棵二叉树,使用非递归的方式实现二叉树左右子树交换,并输出后序遍历结果。完整代码
时间: 2024-05-14 16:18:43 浏览: 78
```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 = [root]
res = []
while stack:
node = stack.pop()
res.append(node.val)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return res[::-1]
def invertTree(root):
if not root:
return None
stack = [root]
while stack:
node = stack.pop()
node.left, node.right = node.right, node.left
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return root
# test
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("Original postorder traversal:", postorderTraversal(root))
invertTree(root)
print("Inverted postorder traversal:", postorderTraversal(root))
```
输出:
```
Original postorder traversal: [1, 3, 2, 6, 9, 7, 4]
Inverted postorder traversal: [9, 6, 7, 3, 1, 2, 4]
```
阅读全文