Topic:
Given an array, determine if it is a two-fork lookup tree after a sequential traversal of an array
Ideas:
Think about the characteristics of binary search tree, any root node is larger than all the values of the left subtree, and all the values of the small less right operand subtree;
Think again, the characteristics of the post-order traversal, first traverse the left subtree, then traverse the right subtree, and finally the root node;
So it is easy to find the root node and then iterate through the array to find the Zuozi (smaller than the root node from left to right), leaving the right subtree on the right, and then judging whether the right subtree is larger than the root node:
If it is, then recursively traverse the left subtree, traverse the right subtree, if all satisfied, it is a binary tree after the sequential traversal array;
If not, it is not.
Code:
#include <iostream>using namespacestd;BOOLIsposttraverse (int*a,intLeftintRight ) { if(left>=Right )return true; Else{ introot=A[right]; intidx=Left ; while(Idx<right && a[idx]<root) idx++; intMid=idx; while(idx<Right ) { if(a[idx]<root)return false; Elseidx++; } BOOLIsleft=isposttraverse (a,left,mid-1); BOOLIsright=isposttraverse (a,mid,right-1); if(Isleft &&isright)return true; Else return false; }}intMain () {inta[]={3,5,8, -,7, the,Ten}; intn=sizeof(A)/sizeof(a[0]); cout<< Isposttraverse (A,0, N-1) <<Endl; return 0;}
Whether the (algorithm) iterates through an array of two-fork lookup numbers