Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/iov3Rain/article/details/90244109
Title Description
A similar data structure node TreeNode, val contains attributes and pointers to other nodes. It can be used to represent a binary search tree (which left pointer represents the left son, right for right pointer son). Please write a method, the binary search tree into a linked list data structure to achieve a binary search tree with TreeNode, linked list data structure with ListNode achieve.
Given a binary search tree root pointer root, converted into a return to head pointer list.
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class Converter {
public:
ListNode* head;
ListNode* cur;
ListNode* treeToList(TreeNode* root)
{
// write code here
head = new ListNode(0);
cur = head;
fun(root);
ListNode *temp = head;
head = head ->next;
delete temp;
return head;
}
void fun(TreeNode* root)
{
if(!root)
return;
fun(root ->left);
cur ->next = new ListNode(root -> val);
cur = cur ->next;
fun(root ->right);
}
};