c++创建二叉树

二叉树 性质

二叉树第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);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值