c_cpp BST
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp BST相关的知识,希望对你有一定的参考价值。
#include <iostream>
using namespace std;
typedef struct node {
int data;
node() : data(0), left(NULL), right(NULL) {}
node(int d) {
data = d;
left = NULL;
right = NULL;
}
struct node* left;
struct node* right;
} Node;
Node* insert(Node* root, int data) {
if (root == NULL)
return new Node(data);
else {
if (data <= root->data) {
cout << "left insert\n";
root->left = insert(root->left, data);
} else {
cout << "right insert\n";
root->right = insert(root->right, data);
}
return root;
}
}
int minValue(Node* node) {
Node* current = node;
/* loop down to find the leftmost leaf */
while (current->left != NULL) {
current = current->left;
}
return(current->data);
}
int maxDepth(Node* node) {
if (node == NULL)
return 0;
int leftDepth = maxDepth(node->left);
int rightDepth = maxDepth(node->right);
int maxDepth = max(leftDepth, rightDepth);
return maxDepth + 1;
}
// A utility function to do inorder traversal of BST
void inorder(Node *root)
{
if (root != NULL)
{
inorder(root->left);
cout << root->data;
inorder(root->right);
}
}
// To execute C++, please define "int main()"
int main() {
Node *root = new Node(10);
root = insert(root, 4);
root = insert(root, 2);
root = insert(root, 1);
root = insert(root, 3);
root = insert(root, 6);
root = insert(root, 5);
inorder(root);
return 0;
}
/*
Your previous Plain Text content is preserved below:
*/
以上是关于c_cpp BST的主要内容,如果未能解决你的问题,请参考以下文章
c_cpp BST搜索
c_cpp BST
c_cpp BST.c
c_cpp BST实施和遍历
c_cpp 二叉搜索树(BST)
c_cpp 排序数组到平衡BST