二叉树 性质
二叉树第i层上的结点数目最多为2的i-1次幂(i>=1)
深度为k的二叉树至多有2k次幂-1个结点(k>=1)
包含n个结点的二叉树的高度至少为log2(n-1)
在任意一棵二叉树中 若终端结点的个数为n0,度为2的结点数为n2,则n0 = n2+1
二叉搜索数
二叉搜索数又叫二叉查找树,其中每个结点都有一个键标识该节点唯一,并且每个键大于左子书上任意节点的键
特点:
若任意节点的左子树不空 则左子树上所有结点的值均小于它的根结点的值
若任意节点的右子树不空 则右子树上所有结点的值均大于它的根结点的值
任意节点的左 右子树也分别为二叉查找树
没有键值相等的点(no duplicate nodes)
#pragma once
using namespace std;
#include<vector>
#include<iostream>
struct Node {
int key;
Node* left = nullptr;
Node* right = nullptr;
Node(int key) {
this->key = key;
}
};
class three
{
private:
Node* root = nullptr;//根节点
public:
three(vector<int> vec);//构造函数
Node* getroot();
void Inorderthree(Node* root);
};
#include "three.h"
three::three(vector<int> vec) {
if (root == nullptr)//创建树的根节点
root = new Node(vec[0]);
for (int i = 1; i < vec.size();i++) {
Node* p = root;
Node* newNode = new Node(vec[i]);//根据vec[i]创建新的节点
while (1) {
if (vec[i] > p->key) {
if (p->right == nullptr) {//如果右子树为空
p->right = newNode;
break;
}
p = p->right;//右子树不为空
}
else if (vec[i] < p->key) {
if (p->left == nullptr) {
p->left = newNode;
break;
} //左子树不为空,与左子树的根节点作比较
p = p->left; //p->left是p的左子树的根节点
}
else if (vec[i] == p->key) {
cout << "有重复key" << endl;
return;
}
}
}
}
Node* three::getroot() {
return root;
}
void three::Inorderthree(Node* root) {
if (root == nullptr)
return;
Inorderthree(root->left);
cout << root->key << " ";
Inorderthree(root->right);
}
#include"three.h"
int main() {
vector<int> vec{7,5,4,6,11,9,10};
three t(vec);
Node* p = t.getroot();
t.Inorderthree(p);
}