【面试题024】二叉搜索树的后序遍历序列

【面试题024】二叉搜索树的后序遍历序列

解决树的问题就是分析,怎么把树的结构一点一点变小,变成子树,

问题的域一直在变小,然后怎么递归的解决这个子问题,

递归这个子问题的返回条件是什么。

 

先找到二叉树的根结点,再基于根结点把整棵树的遍历序列拆分成左子树对应的子序列和右子树对应的子序列,接下来再递归的处理这两个子序列。

 

SquenceOfBST.cpp:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
 
#include <iostream>
#include <cstdio>

using namespace std;

// BST:Binary Search Tree,二叉搜索树
bool VerifySquenceOfBST(int sequence[], int length)
{
    if(sequence == NULL || length <= 0)
        return false;

    int root = sequence[length - 1];

    // 在二叉搜索树中左子树的结点小于根结点
    int i = 0;
    for(; i < length - 1; ++ i)
    {
        if(sequence[i] > root)
            break;
    }

    // 在二叉搜索树中右子树的结点大于根结点
    int j = i;
    for(; j < length - 1; ++ j)
    {
        if(sequence[j] < root)
            return false;
    }

    // 判断左子树是不是二叉搜索树
    bool left = true;
    if(i > 0)
        left = VerifySquenceOfBST(sequence, i);

    // 判断右子树是不是二叉搜索树
    bool right = true;
    if(i < length - 1)
        right = VerifySquenceOfBST(sequence + i, length - i - 1);

    return (left && right);
}

//            10
//         /      \
//        6        14
//       /\        /\
//      4  8     12  16
int main()
{
    int data[] = {48612161410};
    int length = sizeof(data) / sizeof(int);

    if(VerifySquenceOfBST(data, length) == true)
        printf("passed.\n");
    else
        printf("failed.\n");

    return 0;
}

Makefile:

1
2
3
4
5
6
7
8
9
10
11
12
 
.PHONY:clean  
CPP=g++  
CFLAGS=-Wall -g  
BIN=test  
OBJS=SquenceOfBST.o  
LIBS=  
$(BIN):$(OBJS)  
    $(CPP) $(CFLAGS) $^ -o $@ $(LIBS)  
%.o:%.cpp  
    $(CPP) $(CFLAGS) -c $< -o $@  
clean:  
    rm -f *.o $(BIN)  

运行结果:

passed.
posted @ 2014-05-13 16:20  z陵  阅读(800)  评论(0编辑  收藏  举报