面试题精选(76):给定BST先序遍历序列,不构造BST的情况下判断BST是否每个node都只有一个child

题目描述:

Input :    You have been given a sequence of integers. 
               Now without actually constructing BST from the given sequence of integers (assuming the sequence is pre-order) determine if each node of BST has single child (either left or right but not both).
Output :  YES if given integer sequence corresponds to such a BST. otherwise say NO. 
 
Ex:        Say NO for 16,10,8,9,29,27,22. 
               Say YES for 10,19,17,14,15,16

 

 

思路分析:

 

// Obviously if each node has just one child, it must be a list.
// And it's also a path in a decision tree; so each next number must
// be in between it's maximum smaller ancestor and minimum larger ancestor.

 

// 16,10,8,9,29,27,22
// =>
// -inf < 10,8,9,29,27,22 < 16
// =>
// -inf < 8,9,29,27,22 < 10
// =>
// 8 < 9,29,27,22 < 10
// =>
// 9 < 29,27,22 < 10
// => failure
//
//
// 10,19,17,14,15,16 
// =>
// 10 < 19,17,14,15,16 < inf
// =>
// 10 < 17,14,15,16 < 19
// =>
// 10 < 14,15,16 < 17
// =>
// 14 < 15,16 < 17
// =>
// 15 < 16 < 17
// => pass

 

 

 

代码:

 

template
bool IsOneChildPreorderBST(T seq[],int n)
{
    T _max,_min;
    assert(n>=2);
    if(seq[0]<=seq[1])
    {
        _max=seq[1]+1;
        _min=seq[0]-1;
    }
    else
    {
        _max=seq[0]+1;
        _min=seq[1]-1;
    }
    for(int i=1;i    {
        if(seq[i]>_max || seq[i]<_min)
            return false;
        if(seq[i]            _max=seq[i-1];
        else
            _min=seq[i-1];
    }
    return true;
}


int _tmain(int argc, _TCHAR* argv[])
{
    int test1[]={16,10,8,9,29,27,22};   ////NO
    int test2[]={10,19,17,14,15,16};    ////YES
    if(IsOneChildPreorderBST(test1,7))
        cout<<"test1 : YES!/n";
    else
        cout<<"test1 : NO!/n";
    if(IsOneChildPreorderBST(test2,6))
        cout<<"test2 : YES!/n";
    else
        cout<<"test2 : NO!/n";

    system("pause");

 return 0;
}

 

 

 

你可能感兴趣的:(面试题精选(76):给定BST先序遍历序列,不构造BST的情况下判断BST是否每个node都只有一个child)