题解 | #二叉搜索树与双向链表#
二叉搜索树与双向链表
http://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5
中序遍历
首先设置一个全局变量pre,保存中序遍历前一个结点,在中序遍历的过程中完善指针指向即可。
C++代码:
class Solution {
public:
TreeNode *pre;
TreeNode* Convert(TreeNode* pRootOfTree) {
if (!pRootOfTree) return pRootOfTree;
TreeNode *p = pRootOfTree;
while (p->left) {p = p->left;}
inorder(pRootOfTree);
return p;
}
void inorder(TreeNode *root) {
if (!root) return;
inorder(root->left);
root->left = pre;
if (pre) {pre->right = root;}
pre = root;
inorder(root->right);
}
};