Whether the (algorithm) iterates through an array of two-fork lookup numbers

Source: Internet
Author: User

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

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.