解法一:题解 | #二叉搜索树与双向链表#
二叉搜索树与双向链表
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: vector<TreeNode*> ls; void inorder(TreeNode* root) { if (!root) { return; } inorder(root->left); ls.push_back(root); inorder(root->right); } TreeNode* Convert(TreeNode* pRootOfTree) { if (pRootOfTree == NULL) { return nullptr; } inorder(pRootOfTree); if(ls.size() == 1){ return ls[0]; } for (int i = 0; i < ls.size() - 1; i++) { ls[i]->right = ls[i + 1]; ls[i + 1]->left = ls[i]; } return ls[0]; } };
得到二叉搜索树的中序遍历,然后顺序操作节点的左右指针进行连接即可。