按层遍历二叉树

按层遍历二叉树是广度优先的算法,这个算法需要一个队列,最开始将根节点入队,然后处理队列,直到队列为空,这样就处理完了整棵树。

好吧,看起来广度优先遍历是这么的简单,与深度优先不同,广度优先使用队列,见下面的代码。处理一个节点时,如果该节点有左儿子将左儿子入队,如果有右儿子将右儿子入队,这样就会按距离遍历完所有的节点。

#include <iostream>
#include <string>
#include <queue>
using namespace std;

struct tree {
	int value;
	struct tree *lchild;
	struct tree *rchild;
};

struct tree *insert(struct tree *root, int value)
{
	if (root) {
		if (value < root->value) {
			root->lchild = insert(root->lchild, value);
		} else {
			root->rchild = insert(root->rchild, value);
		}
	} else {
		root = new struct tree;
		root->value = value;
		root->lchild = 0;
		root->rchild = 0;
	}
	return root;
}

void print(struct tree *root)
{
	queue<struct tree *> list;
	list.push(root);
	cout << "list:";
	while (!list.empty()) {
		struct tree *node = list.front();
		if (node->lchild)
			list.push(node->lchild);
		if (node->rchild)
			list.push(node->rchild);
		list.pop();
		cout << " " << node->value;
	}
	cout << endl;
}

int main()
{
	struct tree *root = 0;
	root = insert(root, 100);
	root = insert(root, 233);
	root = insert(root,  33);
	root = insert(root,  67);
	root = insert(root, 104);
	root = insert(root,  34);
	root = insert(root,  32);
	root = insert(root, 766);
	root = insert(root, 456);
	print(root);
	return 0;
}


### PTA 平台上的按遍历二叉树实现 在 PTA 平台上,按遍历二叉树是一个常见的题目类型。其实现通常涉及以下几个方面: #### 1. 构建二叉树 构建二叉树可以通过序列和中序列完成[^1]。如果仅提供序列,则可以利用特定标记(如 `#` 表示节点)来解析输入并创建对应的二叉树结构[^2]。 以下是基于序列构建二叉树的 Python 实现代码: ```python class TreeNode: def __init__(self, val=None): self.val = val self.left = None self.right = None def build_tree(preorder): if not preorder: return None root_val = preorder.pop(0) if root_val == &#39;#&#39;: return None node = TreeNode(root_val) node.left = build_tree(preorder) node.right = build_tree(preorder) return node ``` #### 2. 按遍历算法 按遍历的核心在于使用队列辅助操作。每次从队列头部取出当前节点,并将其子节点依次加入队列尾部,直到队列为为止。 下面是按遍历的具体实现代码: ```python from collections import deque def level_order_traversal(root): result = [] queue = deque([root]) while queue: current_node = queue.popleft() if current_node is not None: result.append(current_node.val) queue.append(current_node.left) queue.append(current_node.right) else: result.append(&#39;#&#39;) # 如果遇到节点,可以用 &#39;#&#39; 替代 return &#39;&#39;.join(result).rstrip(&#39;#&#39;) ``` #### 3. 综合应用实例 假设给定序列 `"ABD##E##CF##G##"`,我们可以按照上述方法逐步构建二叉树并执行按遍历。 完整的程如下所示: ```python if __name__ == "__main__": preorder_input = list(input().strip()) # 输入序列 tree_root = build_tree(preorder_input) # 构造二叉树 traversal_result = level_order_traversal(tree_root) # 执行按遍历 print(traversal_result) # 输出结果 ``` 对于样例输入 `"ABD##E##CF##G##"`,其输出应为 `"ABCDEFG"`,表示访问的结果。 --- ### 注意事项 - **输入格式**:需严格按照指定形式输入序列,其中 `#` 表示节点。 - **边界条件处理**:当输入仅为单个节点或完全为时,确保程能够正确返回预期结果[^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值