使用c++实现二叉树的定义、创建、遍历

以下代码实现了二叉树的定义、前序创建、前序遍历

#include
#include
#include//计算代码所需要的时间
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) {}
};

//先序创建二叉树
void creatpreTreenode(TreeNode* &root)
{
    int n;
    cout << "请输入当前结点的val值" << endl;
    cin >> n;
    if (n == 0)
    {
        root == NULL;
        return;
    }
    else
    {
        TreeNode* node = new TreeNode;
        node->val = n;
        root = node;
        creatpreTreenode(root->left);
        creatpreTreenode(root->right);
    }
}

//先序遍历二叉树
void preTree(TreeNode* root)
{
    if (root == NULL)
    {
        return;
    }
    else
    {
        cout << root->val << endl;
        preTree(root->left);
        preTree(root->right);
    }
}

int main()
{
    clock_t starttime, endtime;
    starttime = clock();//计时开始

    TreeNode* root = NULL;
    creatpreTreenode(root);//先序创建二叉树
    preTree(root);//先序遍历二叉树
    
    endtime = clock();//计时结束
    cout << "运行时间为: " << (double)(endtime - starttime) / CLOCKS_PER_SEC << "s" << endl;
    system("pause");
    return 0;
}

你可能感兴趣的:(c++,数据结构与算法,笔记,c++,数据结构,算法,二叉树,前序遍历)