class Solution {
public:
// 递归
bool travel(vector &postorder, int start, int end) {
if (start >= end) return true;
int index = start;
// 寻找第一个大于根节点的值,即找到根节点的右孩子
while (postorder[index] < postorder[end]) index++;
int midindex = index; // 右子树的索引位置
while (postorder[index] > postorder[end]) index++;//将索引走到不大于end的位置,
// 递归左右子树
bool left = travel(postorder, start, midindex – 1);
bool right = travel(postorder, midindex, end – 1);
// 如果index能成功到end的位置,认为这是一个搜索二叉树的后序遍历
return index end && left && right;
}
共以下 11 个回答
class Solution { &postorder, int start, int end) {
public:
// 递归
bool travel(vector
if (start >= end) return true;
int index = start;
// 寻找第一个大于根节点的值,即找到根节点的右孩子
while (postorder[index] < postorder[end]) index++;
int midindex = index; // 右子树的索引位置
while (postorder[index] > postorder[end]) index++;//将索引走到不大于end的位置,
// 递归左右子树
bool left = travel(postorder, start, midindex – 1);
bool right = travel(postorder, midindex, end – 1);
// 如果index能成功到end的位置,认为这是一个搜索二叉树的后序遍历
return index end && left && right;
}
};
二叉树的后序遍历是中右左为遍历顺序的倒序,根据这种方法分离出根节点,左子树右子树。根据搜索树的性质,左子树节点小于根节点,右子树大于,判断是否为true
单独拎出个函数递归
递归
后续遍历序列从第一个大于根节点(序列尾)的开始,后面的都应该大于根节点(右子树)
1、递归
时间复杂度O(n); 空间复杂度O(n)