https://blog.csdn.net/qq_43827595/article/details/104672938
链表创建:
#include <iostream> using namespace std; struct ListNode { int data; ListNode *next; ListNode(int x): data(x), next(NULL) {} }; int main() { // Create a single linked list 1->2->3->4->NULL 1->2->3->4->NULL ListNode *head = new ListNode(-1); ListNode *a = head; for (int i = 1; i <= 4; i ++) { ListNode *b = new ListNode(i); // 尾插法 a->next = b; a = b; } a->next = NULL; // 遍历输出链表 ListNode *p = head->next; while(p != NULL) { printf("%d ", p->data); p = p->next; } puts(""); return 0; }
二叉树创建:
#include <iostream> using namespace std; // 定义二叉树结点 struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x) , left(NULL) , right(NULL) { } }; // 核心:构建一棵二叉树 input数据必须是二叉树前序遍历结果,用-1表示空结点 /* tree: 3 5 -1 -1 -1 input: 3 5 -1 -1 -1 */ TreeNode *buildTree() { int d; cin >> d; if (d == -1) return NULL; TreeNode *root = new TreeNode(d); root->left = buildTree(); root->right = buildTree(); return root; } // 二叉树的中序遍历 void inorderTraversal(TreeNode *root) { if (root == NULL) return; inorderTraversal(root->left); cout << root->val << " "; inorderTraversal(root->right); } int main() { auto root = buildTree(); inorderTraversal(root); return 0; }
输入数据:3 4 -1 -1 5 -1 -1
输出结果:4 3 5