[剑指Offer] 26.二叉搜索树与双向链表
【思路】因为二叉搜索树的中序遍历就是递增排列的,所以只要在中序遍历时将每个结点放入vector中,再分别为每个结点的左右指针赋值即可。
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 { 12 public: 13 vector<TreeNode *> nodeVector; 14 15 void inOrder(TreeNode* root) 16 { 17 if(root->left) 18 inOrder(root->left); 19 nodeVector.push_back(root); 20 if(root->right) 21 inOrder(root->right); 22 } 23 24 TreeNode* Convert(TreeNode* pRootOfTree) 25 { 26 if((pRootOfTree == NULL) || (!pRootOfTree->left) && (!pRootOfTree->right)) 27 return pRootOfTree; 28 inOrder(pRootOfTree); 29 nodeVector[0]->left = NULL; 30 nodeVector[0]->right = nodeVector[1]; 31 int i = 1; 32 for( ; i < nodeVector.size() - 1; i ++) 33 { 34 nodeVector[i]->left = nodeVector[i - 1]; 35 nodeVector[i]->right = nodeVector[i + 1]; 36 } 37 nodeVector[i]->left = nodeVector[i - 1]; 38 nodeVector[i]->right = NULL; 39 return nodeVector[0]; 40 } 41 };