微软算法面试(7):判断整数序列是不是二元查找树的后序遍历结果

题目:输入一个整数数组,判断该数组是不是某二元查找树的后序遍历结果
如果是返回true,否则返回false。

分析:
问题的关键是要找到二元查找树的后序遍历结果,字符串的比较很简单。

下面看看实现:
输入整数序列为:5,7,6,9,11,10,8
二元查找树:
8
/ /
6 10
/ / / /
5 7 9 11

此二元查找树的后序遍历结果为:5,7,6,9,11,10,8
由此可判断 返回true.

#include<iostream>
#include<stdlib.h>
#include<stdio.h>
using namespace std;

struct BTree{
        BTree(int _v = 0):value(_v),left(NULL),right(NULL) {}
        int value;
        BTree* left;
        BTree* right;
        void add(BTree* _bt)
        {
                if(value > _bt->value)
                {
                        if(left == NULL)
                                left = _bt;
                        else
                                left->add(_bt);
                }
                else
                {
                        if(right == NULL)
                                right = _bt;
                        else
                                right->add(_bt);
                }
        }
};

void endfindBTree(BTree* bt, string& strRes)
{
        if(bt == NULL) return;
        if(bt->left != NULL) endfindBTree(bt->left, strRes);
        if(bt->right != NULL) endfindBTree(bt->right, strRes);
        char _str[10];
        sprintf(_str, "%d", bt->value);
        strRes += _str;
}

bool bEQStr(const string& str1, const string& str2)
{
        if(str1 == str2)
                return true;
        else
                return false;
}

int main()
{
        BTree* root;
        BTree bt1(8);
        BTree bt2(6);
        BTree bt3(10);
        BTree bt4(5);
        BTree bt5(7);
        BTree bt6(9);
        BTree bt7(11);

        root = &bt1;
        root->add(&bt2);
        root->add(&bt3);
        root->add(&bt4);
        root->add(&bt5);
        root->add(&bt6);
        root->add(&bt7);

        char instr[] = "576911108";

        string str = "";
        endfindBTree(root, str);
         cout << str.c_str() << endl;
        cout << instr << endl;
        if(bEQStr(str, instr))
                cout << "result(str, BTree)  is Equal"  <<endl;
        else
                cout << "result(str, BTree)  is not Equal" <<endl;
        return 0;
}
posted @ 2021-01-29 22:53  天涯学馆  阅读(97)  评论(0编辑  收藏  举报