2.编写非递归遍历算法,实现:给定一棵二叉树的先序通历序列和中序通历序列,创建这棵二叉树。 (1 输出二叉树的后序遍历的结点序列。 (2)输出二叉树的叶子结点。 (3)统计二叉树的结点个数。
时间: 2024-01-23 22:49:35 浏览: 86
1. 非递归遍历算法示例代码:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def buildTree(preorder, inorder):
if not preorder or not inorder:
return None
root = TreeNode(preorder[0])
stack = [root]
inorderIndex = 0
for i in range(1, len(preorder)):
node = TreeNode(preorder[i])
if node.val != stack[-1].val:
stack[-1].left = node
else:
while stack and stack[-1].val == node.val:
lastNode = stack.pop()
inorderIndex += 1
lastNode.right = node
stack.append(node)
return root
```
2. 输出二叉树的后序遍历的结点序列:
```python
def postorderTraversal(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
```
3. 输出二叉树的叶子结点:
```python
def getLeafNodes(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)
else:
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return result
```
4. 统计二叉树的结点个数:
```python
def getNodeCount(root):
if not root:
return 0
count = 0
stack = [root]
while stack:
node = stack.pop()
count += 1
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return count
```
阅读全文