刷题平台:牛客网
题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
思路:将二叉排序树中序遍历即得到一个有序序列,题目的关键是如何转化为一个双向链表,即修改左右孩子指针,需要使用一个pre指针辅助进行修改。
C++非递归实现:
class Solution { public: TreeNode* Convert(TreeNode* pRootOfTree) { if(!pRootOfTree) return NULL; stack<TreeNode*> S; TreeNode *p = pRootOfTree; TreeNode *pre; //对中序遍历的第一个结点特殊处理 TreeNode *first; bool isFirst = true; //非递归中序遍历 while(p||!S.empty()){ if(p){ S.push(p); p = p->left; }else{ p = S.top(); S.pop(); if(isFirst){ first = p; pre = first; isFirst = false; }else{ pre->right = p; p->left = pre; pre = p; } p = p->right; } } return first; } };
java递归实现:
public class Solution { public TreeNode pre = null; public TreeNode Convert(TreeNode pRootOfTree) { if(pRootOfTree == null) return null; InOrder(pRootOfTree); TreeNode p = pRootOfTree; while(p.left != null) p = p.left; return p; } public void InOrder(TreeNode pRootOfTree) { if(pRootOfTree != null){ InOrder(pRootOfTree.left); pRootOfTree.left = pre; if(pre!=null) pre.right = pRootOfTree; pre = pRootOfTree; InOrder(pRootOfTree.right); } } }