(方法)利用层序遍历返回二叉树上的节点

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/alex1997222/article/details/82944988

我们在查找二叉树上的节点时,会通过递归去进行遍历,如果我们要把这个节点作为函数返回值进行返回的话,递归遍历法就无法满足

我们可以通过层序遍历去查找结点然后进行返回,只需一个辅助队列就行

中序遍历的思想很简单

(1)先将父亲结点入队

(2)如果父亲结点的左子不为空,左子入队

(3)如果父亲结点的右子不为空,右子入队

(4)父亲结点出队

(5)重复上述操作直到队列为空

我们通过层序遍历去查找指定结点,找到后进行返回即可,代码如下

Node* layerfindNode(char node) {
		if (root != nullptr) {
			nodeQueue.push(root);
			while (!nodeQueue.empty()) {
				if (nodeQueue.front()->data == node) {
					return nodeQueue.front();
					break;
				}
				else {
					if (nodeQueue.front()->lchild != nullptr) {
						nodeQueue.push(nodeQueue.front()->lchild);
					}
					if (nodeQueue.front()->rchild != nullptr) {
						nodeQueue.push(nodeQueue.front()->rchild);
					}
					nodeQueue.pop();
				}
			}
		}
		return nullptr;
	}

猜你喜欢

转载自blog.csdn.net/alex1997222/article/details/82944988
今日推荐