Wins the offer - 35 postorder traversal of a binary tree

Title Description

Enter an integer array, the array is not the result of the determination after traversing a binary search tree. If the output Yes, otherwise the output No. Suppose the input array of any two numbers are different from each other.
 
answer:
  This question first thought preorder obtained after the postorder sorted, and then using a preorder traversal sequence after recombination binary tree, but not necessarily because BST postorder traversal of the tree, so that the resulting preorder It may not be correct;
  Therefore, according to the postorder traversal, directly to the left and right subtrees of the tree is determined.
  
 1 class Solution {
 2 public:
 3     bool VerifySquenceOfBST(vector<int> sequence) {
 4         if (sequence.size() == 0)return false;
 5         return isBST(sequence, 0, sequence.size() - 1);
 6     }
 7     bool isBST(vector<int>v, int L, int R)
 8     {
 9         if (L >= R)return true;
10          int the root = V [R & lt];
 . 11          int I = L;
 12 is          the while ; (V [I] <the root) ++ I // find the left subtree 
13 is          int J = I;
 14          the while (J <R & lt) IF ( V [J ++] <the root) return  to false ; // Analyzing the right subtree 
15          return isBST (V, L, I - . 1 ) && isBST (V, I, R & lt - . 1 );    
 16      }    
 . 17 };

 

Guess you like

Origin www.cnblogs.com/zzw1024/p/11681930.html