IT company 100 question-9-judge whether the integer sequence is the result of the Binary Search Tree's descending order traversal

Source: Internet
Author: User
Problem description:Enter an integer array to determine whether the array is the result of the sequential traversal of a binary search tree. If true is returned, otherwise false is returned. For example, input 4, 8, 6, 12, 16, 14, 10, because the integer sequence is the result of the post-order traversal of the following tree: 10
/\
6 14
/\/\
4 8 12 16 therefore, true is returned. If you enter 6, 5, 8, 5, 7, false is returned. Analysis:

In the subsequent traversal sequence, the last element is the root node of the tree. The root node element divides the array into two parts. The left side is smaller than the root node, and the right side is greater than the root node. Recursively determine whether the left and right are binary search trees.

Code implementation:

1 // 9.cc 2 # include <iostream> 3 using namespace STD; 4 5 bool verify (int * a, int size) {6 if (null = A | size <= 0) 7 return false; 8 9 int root = A [size-1]; 10 11 // The left node is smaller than the root node 12 INT I = 0; 13 while (I <size-1 & A [I] <= root) 14 I ++; 15 16 // The right node is 17 for (Int J = I; j <size-1; j ++) {18 if (a [J] <root) 19 Return false; 20} 21 22 // verify left and right subtree 23 bool left = true; 24 if (I> 0) 25 left = verify (A, I ); 26 27 bool right = true; 28 if (I <size-1) 29 right = verify (a + I, size-I-1 ); 30 31 return (left & right); 32} 33 34 int main () {35 int A [] = {4, 8, 6, 12, 16, 14, 10}; 36 int size = sizeof (a)/sizeof (INT); 37 bool flag = verify (A, size); 38 cout <flag <Endl; 39 return 0; 40}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.