题解 | #二叉搜索树与双向链表#
二叉搜索树与双向链表
https://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } };*/ class Solution { public: // 保存当前遍历结点的前一个遍历结点 TreeNode* pre = nullptr; // 记录返回链表的头结点 TreeNode* head = nullptr; // 记录结点是否为链表中的第一个结点 bool flag = false; TreeNode* Convert(TreeNode* pRootOfTree) { if (pRootOfTree != nullptr) { Convert(pRootOfTree->left); if (pRootOfTree->left==nullptr && flag == false) { head = pRootOfTree; flag = true; } if (pre != nullptr) { pre->right = pRootOfTree; pRootOfTree->left = pre; } pre = pRootOfTree; Convert(pRootOfTree->right); } return head; } };