-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBST.cpp
More file actions
60 lines (53 loc) · 1.13 KB
/
BST.cpp
File metadata and controls
60 lines (53 loc) · 1.13 KB
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
60
//
// BinarySerachTree.cpp
// test
//
// Created by KevinLiu on 16/12/22.
// Copyright © 2016年 KevinLiu. All rights reserved.
//
#include <iostream>
typedef struct node
{
int value;
node * pLeft;
node * pRight;
node(int val = 0)
{
value = val;
pRight = NULL;
pLeft = NULL;
}
}node;
void insert(node ** pRoot, int val)
{
if(*pRoot == NULL)
*pRoot = new node(val);
else if((*pRoot)->value <= val)
insert(&((*pRoot)->pRight), val);
else if((*pRoot)->value > val)
insert(&((*pRoot)->pLeft), val);
}
node * getBST(int * arr, int size)
{
node * pRoot = NULL;
for(int i = 0; i < size; i++)
insert(&pRoot, arr[i]);
return pRoot;
}
void inOrderTraversal(node * pRoot)
{
if(pRoot && pRoot->pLeft)
inOrderTraversal(pRoot->pLeft);
if(pRoot)
std::cout<<pRoot->value<<" , ";
if(pRoot && pRoot->pRight)
inOrderTraversal(pRoot->pRight);
}
int main()
{
int arr[] = {10,5,15,5,6,7,8,89};
node * pRoot = getBST(arr, sizeof(arr)/sizeof(int));
inOrderTraversal(pRoot);
std::cout<<std::endl;
return 0;
}