二叉判定树的构造(C++)

二叉树的构造

#include<bits/stdc++.h>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

TreeNode* make(vector<int> arr, int l, int r){
    // 递归构造
    if (l > r) return nullptr;
    int mid = (l + r + 1) / 2;
    TreeNode* lt = make(arr, l, mid - 1);
    TreeNode* rt = make(arr, mid + 1, r);
    return new TreeNode(arr[mid], lt, rt);
}
TreeNode* makeBSTree(vector<int> arr) {
    TreeNode* root;
    // 递归构造
    sort(arr.begin(), arr.end());
    return make(arr, 0, arr.size() - 1);
}
int getDepth(TreeNode* root){
    if (root == nullptr) { return 0; }
    return max(getDepth(root->left), getDepth(root->right)) + 1;
}
void preOrder(TreeNode* root){
    if (root == nullptr) return;
    cout << root->val << " ";
    preOrder(root->left);
    preOrder(root->right);
}
void inOrder(TreeNode* root){
    if (root == nullptr) return;
    preOrder(root->left);
    cout << root->val << " ";
    preOrder(root->right);
}

结果验证

由于前序遍历和中序遍历可以唯一的确定一棵子树,因而本次实验对结果输出前序遍历和中序遍历结果。

void preOrder(TreeNode* root){
    if (root == nullptr) return;
    cout << root->val << ", ";
    preOrder(root->left);
    preOrder(root->right);
}
void inOrder(TreeNode* root){
    if (root == nullptr) return;
    inOrder(root->left);
    cout << root->val << ", ";
    inOrder(root->right);
}
int main(){
    vector<int> arr(10);
    for (int i = 1; i <= 10; ++i) arr[i-1] = i;
    TreeNode* root = makeBSTree(arr);
    for (int i = 0; i < 10; ++i) cout << arr[i] <<  " ";
    cout << endl;
    preOrder(root);
    cout << endl;
    inOrder(root);
    return 0;
}

输出结果

preOrder: 6, 3, 2, 1, 5, 4, 9, 8, 7, 10
inOrder: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,

事实上这棵树的层序遍历为:

[6,3,9,2,5,8,10,1,null,4,null,7]

将其可视化为:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值