C++ Level-Order Traversal

这里讲讲对binary Tree 进行level order Traversal.。 即BF traversal(广度优先遍历)。即首先, 访问根节点F, 打印出数据。 接着访问level 1的所有节点, 即D, J。 访问完level1之后, 访问level2, 即B, E, G , K 等等一次访问下去, 直至遍历完所有的节点。

 

BFS遍历的思路很简单, 但是当我们编程实现的时候, 却会遇到问题的。

首先当我们访问完节点D的时候u, 我们并不能够直接从D到达J, 因为D的指针并没有指向J。

 

clearly, 只用一个指针是不够的。  我们的解决办法是, 当我们在访问一个节点的时候, 我们将这个节点的所有的孩子(children)的地址保存在一个queue中, so that we can visit them later。

 

A node in a queue can be called discovered node,but has not visited yet。

例如, 树的各个节点的存储位置如下标记的。 最开始, 我们从根节点开始, 将root node 标记为discovered node, 存储到queue中:

注意只要我们的queue不是empty的, 我们就可以从queue中取出这个地址, 访问树的相关的节点(例如打印节点的数据)。

接下来, 我们enqueue the children of the root node , 得到:

接下来, 我们从queue中(dequeue)200 的地址, 访问这个节点, 打印出数据(为D), 然后enqueue the childen of the node with D, 得到如下:

 

接下来, 同理, 直至我们访问完所有的节点, queue(FIFO)也变成NULL了。

NOTE: queue的先进先出保证了我们能够实现BF Traversal.。

 

下面我们编程实现(C++):

/* Binary tree - Level Order Traversal */
#include<iostream>
#include<queue>
using namespace std;

struct Node {
	char data;
	Node *left;
	Node *right;
};

// Function to print Nodes in a binary tree in Level order
void LevelOrder(Node *root) {
	if(root == NULL) return;
	queue<Node*> Q;
	Q.push(root);
	//while there is at least one discovered node
	while(!Q.empty()) {
		Node* current = Q.front();
		Q.pop(); // removing the element at front
		cout<<current->data<<" ";
		if(current->left != NULL) Q.push(current->left);
		if(current->right != NULL) Q.push(current->right);
	}
}
// Function to Insert Node in a Binary Search Tree
Node* Insert(Node *root,char data) {
	if(root == NULL) {
		root = new Node();
		root->data = data;
		root->left = root->right = NULL;
	}
	else if(data <= root->data) root->left = Insert(root->left,data);
	else root->right = Insert(root->right,data);
	return root;
}

int main() {
	/*Code To Test the logic
	  Creating an example tree
                M
			   / \
			  B   Q
			 / \   \
			A   C   Z
    */
	Node* root = NULL;
	root = Insert(root,'M'); root = Insert(root,'B');
	root = Insert(root,'Q'); root = Insert(root,'Z');
	root = Insert(root,'A'); root = Insert(root,'C');
	//Print Nodes in Level Order.
	LevelOrder(root);
}


运行结果:

  

下面对上述的遍历算法做一个分析:

首先时间复杂度为O(n), 因为每一个节点只访问了一次。

其次空间复杂度, 由于我们的queue是dynamic的, 所以空间复杂度(是算法所需要的extra memeroy), 需要分情况。

最好的的情况下:

 

对于最坏的情况, 也就是完美的二叉树, 空间复杂度达到O(n):

综合来看Average case下, 算法空间复杂度达到O(n) :

 

 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
代码改进,用printf代替cout。#include <iostream> #include <queue> #include <string> using namespace std; struct Student { string name; int number; int score; }; struct TreeNode { Student data; TreeNode* left; TreeNode* right; TreeNode(Student s) : data(s), left(nullptr), right(nullptr) {} }; void inOrder(TreeNode* root) { if (!root) return; inOrder(root->left); cout << root->data.name << " " << root->data.number << " " << root->data.score << endl; inOrder(root->right); } TreeNode* insert(TreeNode* root, Student s) { if (!root) return new TreeNode(s); if (s.number < root->data.number) { root->left = insert(root->left, s); } else { root->right = insert(root->right, s); } return root; } TreeNode* search(TreeNode* root, string name) { if (!root) return nullptr; if (name == root->data.name) { return root; } else if (name < root->data.name) { return search(root->left, name); } else { return search(root->right, name); } } void print(TreeNode* root) { if (!root) return; if (root->data.score <= 75) { cout << root->data.name << " " << root->data.number << " " << root->data.score << endl; } print(root->left); print(root->right); } int main() { Student students[] = { {"Lei Zhenzi", 101401, 82}, {"Jiang Ziya", 100032, 90}, {"Ne Zha", 101674, 70}, {"Shen Gongbao", 101982, 87}, {"Jiu Weihu", 107431, 75}, {"Tian Zun", 100001, 98}, {"Tai Yi", 101009, 81}, {"Yang Jian", 101321, 63}, {"Huang Feihu", 101567, 72}, {"Zhou Wang", 108160, 55}, {"Li Jing", 102456, 84}, {"Tu Xingsun", 102245, 65}, }; int n = sizeof(students) / sizeof(Student); TreeNode* root = nullptr; for (int i = 0; i < n; i++) { root = insert(root, students[i]); } cout << "In-order traversal: " << endl; inOrder(root); cout << "Level-order traversal: " << endl; queue<TreeNode*> q; q.push(root); while (!q.empty()) { TreeNode* node = q.front(); q.pop(); if (node) { cout << node->data.name << " " << node->data.number << " " << node->data.score << endl; q.push(node->left); q.push(node->right); } } cout << "Search for Tai Yi: " << endl; TreeNode* node = search(root, "Tai Yi"); if (node) { cout << node->data.name << " " << node->data.number << " " << node->data.score << endl; } else { cout << "Not found." << endl; } cout << "Students with score <= 75: " << endl; print(root); return 0; }
最新发布
05-22

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值