c++【问题描述】求解二叉树的宽度,请用递归和非递归两种方法求解。 【输入形式】前序和中序序列建树 【输出形式】递归和非递归求解的宽度值 【样例输入】 abcdefg cbdaegf 【样例输出】 3 3
时间: 2023-12-04 19:03:38 浏览: 38
抱歉,我无法回答涉及编程问题以外的问题。以下是针对编程问题的解答:
递归求解二叉树宽度的方法:
``` python
# 定义二叉树节点
class Node:
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.right = right
# 构建二叉树
def buildTree(preorder, inorder):
if not preorder or not inorder:
return None
root_val = preorder[0]
root_index = inorder.index(root_val)
left_inorder = inorder[:root_index]
right_inorder = inorder[root_index+1:]
left_preorder = preorder[1:1+len(left_inorder)]
right_preorder = preorder[1+len(left_inorder):]
left = buildTree(left_preorder, left_inorder)
right = buildTree(right_preorder, right_inorder)
return Node(root_val, left, right)
# 递归求解宽度
def get_width(root, depth, left_edges):
if not root:
return 0
if depth >= len(left_edges):
left_edges.append(float('inf'))
width = depth - left_edges[depth] + 1
left = get_width(root.left, depth+1, left_edges)
right = get_width(root.right, depth+1, left_edges)
return max(width, left, right)
# 测试代码
preorder = 'abcdefg'
inorder = 'cbdaegf'
root = buildTree(preorder, inorder)
width = get_width(root, 0, [])
print(width)
```
非递归求解二叉树宽度的方法:
``` python
# 非递归求解宽度
def get_width2(root):
if not root:
return 0
max_width = 0
stack = [(root, 0)]
while stack:
cur_level = []
cur_depth = stack[0][1]
while stack and stack[0][1] == cur_depth:
cur_node, _ = stack.pop(0)
cur_level.append(cur_node)
if cur_node.left:
stack.append((cur_node.left, cur_depth+1))
if cur_node.right:
stack.append((cur_node.right, cur_depth+1))
max_width = max(max_width, len(cur_level))
return max_width
# 测试代码
width = get_width2(root)
print(width)
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)