输入格式: 二叉树将以这样的形式给出: 第一行给出一个正整数N(N<=100),表示二叉树上的节点个数! 接下来N行,每行包含三个整数,i,l,r,分别代表第i个节点的左右孩子! 如果它的左/右孩子为空,则在对应位置给出-1! 题目保证1是根节点! 输出格式: 请你输出它的三种遍历! 第一行输出先序遍历,第二行输出中序遍历,第三行输出后序遍历! 每行末尾无多余空格!
时间: 2023-12-15 16:06:20 浏览: 135
以下是 Python 代码实现:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def buildTree(nodes):
if not nodes:
return None
root = TreeNode(nodes[0][0])
nodeDict = {root.val: root}
for node in nodes:
if node[1] != -1:
nodeDict[node[1]] = nodeDict[node[0]].left = TreeNode(node[1])
if node[2] != -1:
nodeDict[node[2]] = nodeDict[node[0]].right = TreeNode(node[2])
return root
def preOrder(root):
if not root:
return []
stack, res = [root], []
while stack:
node = stack.pop()
res.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return res
def inOrder(root):
if not root:
return []
stack, res = [], []
node = root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
res.append(node.val)
node = node.right
return res
def postOrder(root):
if not root:
return []
stack, res = [root], []
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]
n = int(input())
nodes = [list(map(int, input().split())) for _ in range(n)]
root = buildTree(nodes)
print(' '.join(map(str, preOrder(root))))
print(' '.join(map(str, inOrder(root))))
print(' '.join(map(str, postOrder(root))))
```
时间复杂度:$O(n)$,其中 $n$ 是二叉树的节点个数。
阅读全文