牛客对应题目链接:二叉搜索树与双向链表_牛客题霸_牛客网 (nowcoder.com)
力扣对应题目链接:LCR 155. 将二叉搜索树转化为排序的双向链表 - 力扣(LeetCode)
一、《剑指 Offer》对应内容
二、分析题目
上面力扣上的这道题目和牛客上的不太一样,力扣上的是双向循环链表,而牛客上的并不是循环链表,所以返回的是头结点。
三、代码
//牛客
/*
struct TreeNode {int val;struct TreeNode *left;struct TreeNode *right;TreeNode(int x) :val(x), left(NULL), right(NULL) {}
};*/
class Solution {
public:void InOrderConvert(TreeNode* cur, TreeNode*& prev) {if(cur==nullptr) return;InOrderConvert(cur->left, prev);cur->left=prev;if(prev)prev->right=cur;prev=cur;InOrderConvert(cur->right, prev);}TreeNode* Convert(TreeNode* pRootOfTree) {TreeNode* prev=nullptr;InOrderConvert(pRootOfTree, prev);TreeNode* head=pRootOfTree;while(head && head->left)head=head->left;return head;}
};
//力扣
/*
// Definition for a Node.
class Node {
public:int val;Node* left;Node* right;Node() {}Node(int _val) {val = _val;left = NULL;right = NULL;}Node(int _val, Node* _left, Node* _right) {val = _val;left = _left;right = _right;}
};
*/
class Solution {
public:void InOrderConvert(Node* cur, Node*& prev) {if(cur==nullptr) return;InOrderConvert(cur->left, prev);cur->left=prev;if(prev)prev->right=cur;prev=cur;InOrderConvert(cur->right, prev);}Node* treeToDoublyList(Node* root) {if(root==nullptr) return nullptr;Node* prev=nullptr;InOrderConvert(root, prev);Node* head=root;Node* tail=root;while(head && head->left)head=head->left;while(tail && tail->right)tail=tail->right;head->left=tail;tail->right=head;return head;}
};//另一种写法
/*
// Definition for a Node.
class Node {
public:int val;Node* left;Node* right;Node() {}Node(int _val) {val = _val;left = NULL;right = NULL;}Node(int _val, Node* _left, Node* _right) {val = _val;left = _left;right = _right;}
};
*/
class Solution {
private:Node* prev;Node* head;
public:void dfs(Node* cur){if(cur==NULL) return;dfs(cur->left);if(prev) prev->right=cur;else head=cur;cur->left=prev;prev=cur;dfs(cur->right);}Node* treeToDoublyList(Node* root) {if(root==NULL) return NULL;dfs(root);head->left=prev;prev->right=head;return head;}
};