题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
1 /* 2 struct TreeNode { 3 int val; 4 struct TreeNode *left; 5 struct TreeNode *right; 6 TreeNode(int x) : 7 val(x), left(NULL), right(NULL) { 8 } 9 };*/ 10 class Solution { 11 public: 12 std::vector<TreeNode*> vv; 13 void inorder(TreeNode* root) 14 { 15 if (root ->left != NULL) 16 { 17 inorder(root->left); 18 } 19 vv.push_back(root); 20 if(root->right != NULL) 21 { 22 inorder(root->right); 23 } 24 } 25 TreeNode* Convert(TreeNode* pRootOfTree) 26 { 27 if (pRootOfTree == NULL) 28 return NULL; 29 inorder(pRootOfTree); 30 31 if(vv.size() == 1) 32 return pRootOfTree; 33 34 vv[0]->left = NULL; 35 vv[0]->right = vv[1]; 36 int i = 1; 37 for (i; i <= vv.size() - 2; ++i) 38 { 39 vv[i]->left = vv[i-1]; 40 vv[i]->right = vv[i+1]; 41 } 42 vv[i]->left = vv[i-1]; 43 vv[i]->right = NULL; 44 return vv[0]; 45 } 46 };