C++ 单链表以及二叉树简单结构体的书写

简单二叉树:

#include<iostream>
#include<vector>
using namespace std;

//Definition for a binary tree node
struct TreeNode{
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

vector<int> tmp;
void preOrder(TreeNode* root);

int main(){
    TreeNode* root = new TreeNode(5);
    TreeNode* lchild = new TreeNode(3);
    TreeNode* rchild = new TreeNode(8);

    root->left = lchild;
    root->right = rchild;

    preOrder(root);

    for(auto x : tmp)
        cout << x << " ";
    cout << endl;
}

void preOrder(TreeNode* root){
    if(!root)
        return ;
    tmp.push_back(root->val);
    preOrder(root->left);
    preOrder(root->right);
}


简单单链表:
#include<iostream>

using namespace std;

//Definition for singly-linked  list
struct ListNode{
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(NULL){}
};

int main(){
    ListNode* head = new ListNode(1);
    ListNode* p = new ListNode(5);
    head->next = p;
    while(head){
        cout << head->val << endl;
        head = head->next;
    }
}

猜你喜欢

转载自blog.csdn.net/qq249356520/article/details/89225006