Determine whether an array is a result of post-order traversal of a binary sorting tree

Source: Internet
Author: User

For example, an array [, 10, 8] is given to determine whether it is a result of post-order traversal of a binary sorting tree, that is, whether a binary sorting tree can be drawn so that the result of the post-order traversal is the same as that of this array. If true is returned, false is not returned.

Code:

Int is_valid (int * data, int N) {If (Data = NULL) return 0; int left = 1; int right = 1; int I = 0; Int J; int root = data [n-1]; while (data [I] <root) {I ++;} For (j = I + 1; j <n-1; j ++) {If (data [J] <root) {return 0 ;}} if (I> 0) {left = is_valid (data, I) ;}if (j <n-1) {right = is_valid (data, j) ;}return (left & right );}

Ideas:

The last number of arrays must be the root node. Then, traverse from the beginning and find the first junction less than the root node and greater than the root node, continue to traverse the number from this number to the root node. If there is a number smaller than the root node (theoretically, the number from the slave point to the root node should be greater than the root node, because they are in the right subtree of the root node .) Then false is returned.

Then recursion...

Determine whether an array is a result of post-order traversal of a binary sorting tree

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.