【剑指Offer33-二叉树搜索树的后序遍历】

题目:
在这里插入图片描述
这题的单调栈做法十分不好想,因为要有十足的观察力才行。
这里我使用的是一般通解,即递归法:

对每一个区间都去找到左右子树的分割节点,然后判断是否所有右子树(因为左子树元素在划分时能保证都小于当前遍历时的根节点)元素都满足这个条件。如果满足,就继续递归。

C++(附带测试,二叉搜索树请使用数组创建)

#include<iostream>
#include<vector>
#include<set>

using namespace std;

struct TreeNode{
	int val;
	TreeNode* left;
	TreeNode* right;
	TreeNode(int val):val(val),left(nullptr),right(nullptr){}
};

TreeNode* insert(TreeNode* root,int val){
	if(root==nullptr){
		root = new TreeNode(val);
		return root;
	}
	else if(val<root->val){
		root->left = insert(root->left,val);
	}
	else if(val>root->val){
		root->right = insert(root->right,val);
	}
	
	return root;
}

TreeNode* createTree(vector<int> a){
	TreeNode* root = new TreeNode(a[0]);
	for(int i=1;i<a.size();i++){
		root = insert(root,a[i]);
	}
	return root;
}


void inorder(TreeNode* root){
	if(root==nullptr){
		return;
	}
	inorder(root->left);
	cout<<root->val<<" ";
	inorder(root->right);
}

class Solution {
public:
    bool verifyPostorder(vector<int>& postorder) {
		return recur(postorder,0,postorder.size()-1);
    }
    
    bool recur(vector<int>& postorder,int left,int right){
    	if(left>=right){
    		return true;
		}
		int i = left;
		while(postorder[i]<postorder[right]){
			i++;
		}
		int j = i-1;
		while(postorder[i]>postorder[right]){
			i++;
		}
		if(i<right){
			return false;
		}
		
		return recur(postorder,left,j)&&recur(postorder,j+1,right-1);
	}
};

class Solution {
public:
    bool digui(int front,int tail,vector<int>& postorder){
        if(front >= tail) return true;
        int index=front;
        while(postorder[index] < postorder[tail]){
            index++;
        }
        int leftTail = index-1;
        while(postorder[index] > postorder[tail]){
            index++;
        }
        if(index < tail) return false;

        return digui(front,leftTail,postorder) && digui(leftTail+1,tail-1,postorder);
    }

    bool verifyPostorder(vector<int>& postorder) {
        return digui(0,postorder.size()-1,postorder);
    }
};

int main(){
	vector<int> a = {5,6,2,3,1};
	TreeNode* root = createTree(a);
	inorder(root);
	 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值