[英]How to check if a given array represents postorder traversal of Binary Search Tree?
有一个给定的数组,我们需要知道它是否表示BST的后遍历。 (例如:如果问题是有序的,而不是后序的,我们只需要检查数组是否在o(n)的时间排序)
快速的健全性检查:如果数组中的最后一项不是根节点,则不是后遍历的结果。 同样,如果完成了遍历,则数组中的第一项就是根。
后移遍历是通过{左子树} {右子树} {ROOT}完成的。 因此,这里的想法是从右端开始遍历数组。 数组中的最后一个元素是根,当您遇到较小的元素时,从右到左,这标志着从左子树开始的边界,BST不会从该索引中获得更大的元素,这适用于每个子树。 C ++中的算法是这样的-
bool isBST(int arr[], int n){
//Set root to the max integer value.
int root = INT_MAX;
//Stack used to keep track of current subtree
std::stack<int>s;
//Start at the end of the array because Postorder traversal is
// <L><R><D>
for (int i = n-1; i>=0; i--) {
//False if any larger number in the left subtree
if (arr[i]> root) {
return false;
}
//Reset the root for boundary of every subtree,
//when current item is smaller than top,
//that means we are starting with left subtree of this root
while (!s.empty() && arr[i] < s.top()) {
root = s.top();
s.pop();
}
//Keep pushing the elements otherwise
s.push(arr[i]);
}
return true;
}
使用以下代码,可以估计给定数组是否可以表示BST。
程序:
10
/ \
7 12
/ \ \
6 9 31
/
14
令数组为arr = {6,9,7,14,31,12,10}
现在,我们从头开始遍历数组,直到到达元素小于end_index(arr [end_index] = 10)的索引为止。然后将该索引存储在temp中。 (这里temp = 2,即arr [temp] = 7等于7 <10),我们再次从temp遍历直到start_index。 如果找到大于10(最后一个索引的元素)的数字,则返回false。如果不是,则遍历start_index。 现在我们将数组分成两半{6,9,7}和{14,31,12,10}。 并遵循相同的步骤。
逻辑:
发布顺序表示{{LEFT个元素},{RIGHT个元素},{ROOT}}。 因此数组的顺序应为{(元素小于父元素),(元素大于父元素),(父元素)}
这就是我们在遍历数组时要确保的。
代码如下:
public class ckeckIfPostOrderAbinaryTree {
public static void main(String[] args) {
int[] arr={6,9,7,14,31,12,10};
System.out.println(solve(arr,0,arr.length-1));
}
public static boolean solve(int[] arr,int strt,int end){
if(strt>=end){
return true;
}
int x=arr[end],index=end-1;
while(index>=strt && arr[index]>x){
index--;
}
int temp=index;
while(index>=strt){
if(arr[index]>x){
return false;
}
index--;
}
if(temp==strt){
return solve(arr,strt,end-1);
}
else{
return (solve(arr,strt,temp) && solve(arr,temp+1,end-1));
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.