题目:
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
代码:
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 TreeNode* Convert(TreeNode* pRootOfTree) 13 { 14 if( pRootOfTree == NULL) 15 return pRootOfTree; 16 if( pRootOfTree->left == NULL && pRootOfTree->right == NULL ) 17 return pRootOfTree; 18 TreeNode* head = new TreeNode(NULL); 19 //右子树递归(大于根节点的结点) 20 head = Convert(pRootOfTree->right); 21 if(head != NULL){ 22 head->left = pRootOfTree; 23 pRootOfTree->right = head; 24 } 25 //左子树递归(小于根节点的结点) 26 head = Convert(pRootOfTree->left); 27 if(head != NULL){ 28 //此处循环为了找到该子树下最大结点并与此子树根节点相连 29 while(head->right != NULL) 30 head = head->right; 31 head->right = pRootOfTree; 32 pRootOfTree->left = head; 33 } 34 //当此子树的左右枝都排列完毕时,找到最小结点为与根节点相连 35 while(pRootOfTree->left != NULL) 36 pRootOfTree = pRootOfTree->left; 37 return pRootOfTree; 38 } 39 };
我的笔记:
根据二叉搜索树的性质,排列整个双向链表时需要注意,每个子树在回溯到根结点时,要确保返回值,是当前链表的最值,如左子树要返回当前最右(大)结点,右子树要返回当前最左(小)结点。