二叉搜索树的后序遍历【分治+递归】

给定一个序列,我们需要判断此序列是否为某个二叉搜索树的后序遍历序列,题目在二叉搜索树的后序遍历
在这里插入图片描述

  • 二叉搜索树的特点:中序遍历(左->根->右)是一个递增的序列,因此在后序遍历(左->右->根),我们可以判断根的位置,并判断左是否全部小于根,右是否全部大于根,一直判断直到整个序列被遍历
  • 使用left和right指向需要判断的序列的左端点和右端点,根结点就是right指向的值
bool isPost(vector<int>& postorder,int left,int right){
    if(left>=right) return true; //如果遍历完 直接返回true
    int index=0; //index记录左树和右数的分段结点
    int root=postorder[right]; //根结点的值为right指向的值
    while(postorder[index]<root){ //判断左子树是否全部小于根
        index++;
    }
    int temp=index+1; //右子树的起点
    while(temp<right){ //遍历右子树
        if(postorder[temp]<root){ //右子树的值要全部大于root 否则返回false
            return false;
        }
        temp++;
    }
    return isPost(postorder,left,index-1)&&isPost(postorder,index,right-1); //分治,继续向下递归
}
bool verifyPostorder(vector<int>& postorder) {
    int n=postorder.size();
    return isPost(postorder,0,n-1);
}

给定树的中序遍历结果和先序遍历结果,求树的后续遍历结果:

void post(string &inor, string &pre) {
	if (pre.size() == 0) return;
	char root = pre[0]; //根结点是先序遍历序列的第一个值
	int k = inor.find(root); //找到根结点在中序遍历序列中的位置
	pre.erase(pre.begin()); //删去根结点
	string leftpre = pre.substr(0, k);  //求左子树的先序遍历
	string rightpre = pre.substr(k);  //求右子树的先序遍历
	string leftinor = inor.substr(0, k); //求左子树的中序遍历
	string rightinor = inor.substr(k + 1); //求右子树的中序遍历
	post(leftinor, leftpre); //递归左子树的中序和先序序列
	post(rightinor, rightpre);//递归右子树的中序和先序遍历
	cout << root; //记录后序遍历的值
}

int main() {
	string inor, pre;
	cin >> inor >> pre;
	post(inor, pre);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于这个问题,我们可以使用队列和分治法来求解二搜索的层。具体的实现方法如下: 1. 首先,根据后的定义,可以知道二搜索的根节点是列的最后一个元素。 2. 然后,使用分治法将列划分为两个部分,即左子和右子。可以找到第一个比根节点小的元素,将其之前的部分定义为左子的后,之后的部分定义为右子的后。 3. 对于左右子,分别重复上述过程,归求解左右子的层。 4. 最后,将左右子的层按照层次合并起来,即可得到整棵二搜索的层。 下面是具体的实现代码: ```python def postorder_to_levelorder(postorder): if not postorder: return [] root = postorder[-1] mid = bisect.bisect_left(postorder, root) left_postorder = postorder[:mid] right_postorder = postorder[mid:-1] left_levelorder = postorder_to_levelorder(left_postorder) right_levelorder = postorder_to_levelorder(right_postorder) levelorder = [root] queue = [root] while queue: node = queue.pop(0) if node in left_levelorder: levelorder.extend(left_levelorder[left_levelorder.index(node)+1:]) queue.extend(left_levelorder[left_levelorder.index(node)+1:]) if node in right_levelorder: levelorder.extend(right_levelorder[right_levelorder.index(node)+1:]) queue.extend(right_levelorder[right_levelorder.index(node)+1:]) return levelorder ``` 该实现使用了归和队列,时间复杂度为 O(nlogn)。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值