* Prob: Construct a binary seach tree
* Idea: left < root < right, mid order traverse.
* Time: O(nlogn)
* Space:O(n)
* Mistakes: The tree's root is nullptr, so the output is null.
* 2017-06-06
*/
#include<bits/stdc++.h>
using namespace std;
typedef struct BinaryTreeNode{
int value;
int num;
BinaryTreeNode *right;
BinaryTreeNode *left;
}BTNode;
struct Ancestor{
BTNode *node;
BTNode *parent;
bool is_left_child;
};
Ancestor *des_node = nullptr;
BTNode* add_node(BTNode *root, int val){
BTNode *ptr = root;
if(!ptr){
ptr = new BTNode;
ptr->value = val;
ptr->num = 1;
ptr->left = ptr->right = nullptr;
}else{
if(val > ptr->value){
ptr->right = add_node(ptr->right, val);
}else if(val < ptr->value){
ptr->left = add_node(ptr->left, val);
}else{
ptr->num += 1;
}
}
return ptr;
}
BTNode* build_binary_tree(int* ary, int node_num){
BTNode *root = nullptr;
if(node_num<=0) return nullptr;
root = add_node(root, ary[0]);
for(int i=1; i<node_num; i++){
add_node(root, ary[i]);
}
return root;
}
void output_binary_tree(BTNode *root){
if(!root) return;
BTNode* ptr = root;
if(ptr->left){
output_binary_tree(ptr->left);
}
cout<<ptr->value<<":"<<ptr->num<<" ";
if(ptr->right){
output_binary_tree(ptr->right);
}
}
int main(){
int ary[] = {90,12,33,-100,20, 23,12,34,22,78, -1,88,27,9,8, 90,90,33,10,24, 67,54,24,89,120, 44,55,34,100,1};
int node_num = sizeof(ary)/sizeof(ary[0]);
cout<<"Node num:"<<node_num<<endl;
BTNode *root = build_binary_tree(ary, node_num);
cout<<"\nThe Binary Tree is:"<<endl;
output_binary_tree(root);
cout<<endl;
return 0;
}