BST(二叉搜索树)按层遍历

这个是很快的一个充满bug的版本,很快会更新。

按层遍历。

举个例子: 这个BST的话,输出应为1,2,3,4,5,6,7

利用了STL的deque,代码如下:

#include <iostream>
#include <deque>

using namespace std;


struct BSTNode
{
	int      value;
	BSTNode* left;
	BSTNode* right;
	BSTNode()
	{
		value = 0;
		left  = NULL;
		right = NULL;
	}

};

deque<BSTNode*> sq;

void insert(BSTNode* &p, int elem)
	{
		if(p == NULL)
		{
			BSTNode* pnew = new BSTNode();
			pnew->left = 0;
			pnew->right =0;
			pnew->value = elem;
			p = pnew;
			return;
		}
		if(elem > p->value)
		{
			insert(p->right, elem);
		}
		else if(elem < p->value)
		{
			insert(p->left, elem);
		}
		else
			cout << "The Same!" << endl;
	}

void BFS(BSTNode* root)
{
	BSTNode* p = root;
	sq.push_back(p);
	deque<BSTNode*>::iterator i = sq.begin();

	while(p != NULL)
	{	i++;
		sq.push_back(p->left);
		sq.push_back(p->right);
		p = *(i);
	}
}
void print_deque(deque<BSTNode*> que)
{
	deque<BSTNode*>::iterator iter = que.begin();
		for(; iter != que.end(); ++iter)
		{
			cout << (*iter)->value << endl;
		}
}

int main(void)
{
	BSTNode* root = 0;
	insert(root, 8);
	insert(root, 6);
	insert(root, 10);
	insert(root, 5);
	insert(root, 7);
	insert(root, 9);
	insert(root, 11);
	BFS(root);
	print_deque(sq);

	return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
搜索(Binary Search Tree,简称BST)是一种特殊的二,它的每个节点的值都大于其左子中的所有节点的值,且小于其右子中的所有节点的值。根据BST的特性,我们可以通过比较节点的值来确定最近公共祖先。 首先,我们需要根据给定的先序遍序列构建二搜索。构建BST的方法是从根节点开始,依次将序列中的元素插入到中。如果插入的元素小于当前节点的值,则将其插入到左子中;如果插入的元素大于当前节点的值,则将其插入到右子中。 接下来,我们需要找出任意两个节点的最近公共祖先。最近公共祖先是指在二中同时是这两个节点的祖先且深度最大的节点。为了找到最近公共祖先,我们可以从根节点开始遍搜索,根据节点的值与给定两个节点的值的大小关系,不断更新当前节点为其左子或右子中的节点,直到找到最近公共祖先为止。 以下是一个示例代码,演示了如何构建二搜索并找到任意两个节点的最近公共祖先: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def buildBST(preorder): if not preorder: return None root = TreeNode(preorder[0]) i = 1 while i < len(preorder) and preorder[i] < root.val: i += 1 root.left = buildBST(preorder[1:i]) root.right = buildBST(preorder[i:]) return root def findLCA(root, p, q): if not root: return None if p.val < root.val and q.val < root.val: return findLCA(root.left, p, q) elif p.val > root.val and q.val > root.val: return findLCA(root.right, p, q) else: return root # 示例输入 preorder = [6, 2, 0, 4, 3, 5, 8, 7, 9] p = TreeNode(2) q = TreeNode(8) # 构建二搜索 root = buildBST(preorder) # 找到最近公共祖先 lca = findLCA(root, p, q) print("最近公共祖先的值为:", lca.val) ``` 输出结果为: ``` 最近公共祖先的值为: 6 ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值