给出一个先序序列与后序序列相同的二叉树
时间: 2023-12-30 22:06:01 浏览: 68
二叉树的几种操作,包括递归先序建立二叉树、先序遍历、中序遍历、后序遍历、非递归的各种遍历
5星 · 资源好评率100%
一个先序序列与后序序列相同的二叉树可以是一个只有一个节点的二叉树,该节点既是根节点也是叶子节点。具体实现如下:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution:
def constructTree(self, preorder):
if not preorder:
return None
root = TreeNode(preorder[0])
return root
def preorderTraversal(self, root):
if not root:
return []
res = []
res.append(root.val)
res += self.preorderTraversal(root.left)
res += self.preorderTraversal(root.right)
return res
def inorderTraversal(self, root):
if not root:
return []
res = []
res += self.inorderTraversal(root.left)
res.append(root.val)
res += self.inorderTraversal(root.right)
return res
def postorderTraversal(self, root):
if not root:
return []
res = []
res += self.postorderTraversal(root.left)
res += self.postorderTraversal(root.right)
res.append(root.val)
return res
def countLeaves(self, root):
if not root:
return 0
if not root.left and not root.right:
return 1
return self.countLeaves(root.left) + self.countLeaves(root.right)
preorder = [1]
solution = Solution()
root = solution.constructTree(preorder)
print("先序遍历序列:", solution.preorderTraversal(root))
print("中序遍历序列:", solution.inorderTraversal(root))
print("后序遍历序列:", solution.postorderTraversal(root))
print("叶子数:", solution.countLeaves(root))
```
阅读全文