输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
思路,中序遍历压入vector,然后调整
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | /* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; */ class Solution { public : vector<TreeNode *> m_vector; TreeNode* Convert(TreeNode* pRootOfTree) { if (pRootOfTree==NULL) return NULL; printVector(pRootOfTree); for ( int i= 0 ;i<m_vector.size()- 1 ;i++) { m_vector[i]->right=m_vector[i+ 1 ]; m_vector[i+ 1 ]->left=m_vector[i]; } return m_vector[ 0 ]; } void printVector(TreeNode *root) { if (root->left!=NULL) printVector(root->left); m_vector.push_back(root); if (root->right!=NULL) printVector(root->right); } }; |