二叉搜索树转换为双向链表
要求空间复杂度为O(1),两种方法:
1、不严格的O(1),用了递归
2、严格的递归,用了Morris中序遍历(中序遍历在tempNode->right == root时,不需要清零,因为此时prevNode正好等于tempNode)
struct TreeNode { int val; TreeNode *left, *right; TreeNode(int _val) : val(_val), left(nullptr), right(nullptr) { } }; void doubleLinkList(TreeNode *root, TreeNode *&prevNode) { if (root == nullptr) return; doubleLinkList(root->left, prevNode); prevNode->right = root; root->left = prevNode; prevNode = root; doubleLinkList(root->right, prevNode); } void doubleLinkList2(TreeNode *root, TreeNode *prevNode) { while (root) { if (root->left == nullptr) { prevNode->right = root; root->left = prevNode; prevNode = root; root = root->right; } else { TreeNode *tempNode = root->left; while (tempNode->right != nullptr && tempNode->right != root) tempNode = tempNode->right; if (tempNode->right == nullptr) { tempNode->right = root; root = root->left; } else { root->left = prevNode; prevNode = root; root = root->right; } } } } int main() { TreeNode *root = new TreeNode(5); root->left = new TreeNode(3); root->left->left = new TreeNode(1); root->right = new TreeNode(6); TreeNode dummy(0); TreeNode *prevNode = &dummy; //doubleLinkList(root, prevNode); doubleLinkList2(root, prevNode); if (dummy.right != nullptr) dummy.right->left = nullptr; return 0; }