您的位置:首页 > 理论基础 > 数据结构算法

树的计数问题和通过一个中序遍历序列和一个先序遍历序列来确定一棵二叉树

2016-06-07 17:47 489 查看
       


通过一个中序遍历序列和一个先序遍历序列来确定一棵二叉树

用例为://先序:abcdefg 中序: cbedafg
结果为:



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
import
 
java.util.ArrayList;

//通过一个中序遍历序列和一个先序遍历序列来确定一棵二叉树

 
public
 
class
 
TestCase2{

    
 
    
//preOrders先序遍历序列 
midOrders中序遍历序列

    
public
 
static
 
TreeCase getTree(TreeCase tree,ArrayList<Character> preOrders,ArrayList<Character> midOrders){

        
if
(midOrders.isEmpty()) 
return
 
null
;

        
 
        
tree = 
new
 
TreeCase();

        
tree.data = preOrders.get(
0
);

        
 
        
//找到中间位置

        
int
 
index = midOrders.indexOf(preOrders.get(
0
));
//找到当前根节点在中序中的位置,位置左边就是该根节点的左子树

        
preOrders.remove(
0
);                            
//右边就是其右子树

        
 
        
if
(midOrders.size() == 
1
return
 
tree;
//已经是叶子节点了

        
 
        
ArrayList<Character> arr1 = 
new
 
ArrayList<>();
//左子树的中序序列

        
for
(
int
 
i=
0
;i<index;i++){

            
arr1.add(midOrders.remove(
0
));

        
}

        
midOrders.remove(
0
);
//右子树的中序序列

            
 
        
tree.lchild = getTree(tree.lchild,preOrders,arr1);
//构造左子树

        
tree.rchild = getTree(tree.rchild,preOrders,midOrders);
//构造右子树

        
 
        
return
 
tree;

        
 
    
}

 
    
public
 
static
 
void
 
main(String[] args){

        
ArrayList<Character> arr1 = 
new
 
ArrayList<>(
7
);

        
ArrayList<Character> arr2 = 
new
 
ArrayList<>(
7
);

        
 
        
//先序:abcdefg 中序: cbedafg

        
arr1.add(
'a'
); arr1.add(
'b'
); arr1.add(
'c'
); arr1.add(
'd'
); 

        
arr1.add(
'e'
); arr1.add(
'f'
); arr1.add(
'g'
);

        
 
        
arr2.add(
'c'
); arr2.add(
'b'
); arr2.add(
'e'
); arr2.add(
'd'
); 

        
arr2.add(
'a'
); arr2.add(
'f'
); arr2.add(
'g'
);

 
        
TreeCase tree = 
null
;

        
tree = TestCase2.getTree(tree, arr1, arr2);

    
}

}

class
 
TreeCase{

    
char
 
data;

    
TreeCase lchild;

    
TreeCase rchild;

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息