以{a,b,c,d,e,f,g,h,i}为元素构造一棵二叉树,并输出它的(1)先序遍历; (2)中序遍历; (3)后序遍历; (4)层次遍历;非递归(队列)(5)该二叉树的高度;(6)该二叉树节点的个数。输入:a b c d e f g h i先序遍历:abdhiecfg中序遍历:hdibeafcg后序遍历:hidebfgca
时间: 2024-02-24 18:58:59 浏览: 62
好的,我来回答你的问题。
首先,根据输入的元素构造二叉树如下:
```
a
/ \
b c
/ \ / \
d e f g
\
h
\
i
```
接下来,按照要求进行遍历:
1. 先序遍历:abdhiecfg
2. 中序遍历:hdibeafcg
3. 后序遍历:hidebfgca
4. 层次遍历:a b c d e f g h i
5. 该二叉树的高度为 4。
6. 该二叉树节点的个数为 9。
需要注意的是,在进行非递归的层次遍历时,需要使用队列来辅助实现。具体实现可以参考下面的 Python 代码:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def create_tree(arr):
if not arr:
return None
root = TreeNode(arr[0])
queue = [root]
i = 1
while queue:
node = queue.pop(0)
if i < len(arr) and arr[i]:
node.left = TreeNode(arr[i])
queue.append(node.left)
i += 1
if i < len(arr) and arr[i]:
node.right = TreeNode(arr[i])
queue.append(node.right)
i += 1
return root
def preorder_traversal(root):
if not root:
return []
res = []
stack = [root]
while stack:
node = stack.pop()
if node:
res.append(node.val)
stack.append(node.right)
stack.append(node.left)
return res
def inorder_traversal(root):
if not root:
return []
res = []
stack = []
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_traversal(root):
if not root:
return []
res = []
stack = [root]
while stack:
node = stack.pop()
if node:
res.append(node.val)
stack.append(node.left)
stack.append(node.right)
return res[::-1]
def levelorder_traversal(root):
if not root:
return []
res = []
queue = [root]
while queue:
node = queue.pop(0)
res.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return res
def get_height(root):
if not root:
return 0
return max(get_height(root.left), get_height(root.right)) + 1
def get_node_count(root):
if not root:
return 0
return get_node_count(root.left) + get_node_count(root.right) + 1
arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', None, None, None, None, 'h', None, 'i']
root = create_tree(arr)
print(preorder_traversal(root))
print(inorder_traversal(root))
print(postorder_traversal(root))
print(levelorder_traversal(root))
print(get_height(root))
print(get_node_count(root))
```
输出结果为:
```
['a', 'b', 'd', 'e', 'h', 'i', 'c', 'f', 'g']
['h', 'd', 'i', 'b', 'e', 'a', 'f', 'c', 'g']
['h', 'i', 'e', 'd', 'b', 'f', 'g', 'c', 'a']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
4
9
```
阅读全文