Interview question 22: Post-order traversal sequence of the Binary Search Tree

Source: Internet
Author: User


Analysis: in the Post-order traversal sequence, the last number is the value of the root node of the tree. The number before the array can be divided into two parts: the first part is the value of the Left subtree node, they are smaller than the value of the root node. The second part is the value of the right subtree node, which is larger than the value of the root node.

Code:

 

# Include "stdafx. h "# include <iostream> using namespace std; bool VerifySequenceOfBST (int nSequence [], int nLength) {if (nSequence = NULL | nLength <= 0) {return false;} int nRoot = nSequence [nLength-1]; int nIndex = 0; while (nSequence [nIndex] <nRoot) // The value of the node in the left subtree is smaller than the value of the root node {nIndex ++;} for (int I = nIndex + 1; I <nLength; I ++) // The value of the node in the right subtree is greater than the value of the root node {if (nSequence [I] <nRoot) {return false ;}} bool bLeft = true; if (nIndex> 0) {bLeft = VerifySequenceOfBST (nSequence, nIndex);} bool bRight = true; if (nIndex + 1) <nLength) {bRight = VerifySequenceOfBST (nSequence + nIndex, nLength-1-nIndex);} return (bLeft & bRight);} int _ tmain (int argc, _ TCHAR * argv []) {int nArr1 [7] = {5, 7, 6, 9, 11, 10, 8}; // correct sequence, with left and right subtree cout <VerifySequenceOfBST (nArr1, 7) <endl; int nArr2 [4] = {7, 4, 6, 5}; // error sequence cout <VerifySequenceOfBST (nArr2, 4) <endl; int nArr3 [3] = {3, 2, 1}; // right single cout <VerifySequenceOfBST (nArr3, 3) <endl; int nArr4 [3] = {1, 2, 3}; // left single cout <VerifySequenceOfBST (nArr4, 3) <endl; int nArr5 [1] = {1 }; // Single Node cout <VerifySequenceOfBST (nArr5, 1) <endl; system ("pause"); return 0 ;}

 

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.