设计算法求二叉结点的个数:按前序次序打印二叉树中的叶子结点;求二叉树的深度.python代码
时间: 2024-06-13 12:08:06 浏览: 9
以下是Python代码,实现了求二叉树结点个数、按前序次序打印二叉树中的叶子结点以及求二叉树深度的功能:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def createTree(preorder):
if not preorder:
return None
val = preorder.pop(0)
if val == '#':
return None
root = TreeNode(val)
root.left = createTree(preorder)
root.right = createTree(preorder)
return root
def countNodes(root):
if not root:
return 0
return 1 + countNodes(root.left) + countNodes(root.right)
def printLeaves(root):
if not root:
return
if not root.left and not root.right:
print(root.val, end=' ')
printLeaves(root.left)
printLeaves(root.right)
def maxDepth(root):
if not root:
return 0
return 1 + max(maxDepth(root.left), maxDepth(root.right))
while True:
try:
preorder = input().split()
root = createTree(preorder)
print(countNodes(root))
printLeaves(root)
print(maxDepth(root))
except:
break
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)