二叉搜索树与双向链表_牛客题霸_牛客网 (nowcoder.com)
解题思路 :
根据题目要求 : 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表. 一颗二叉搜索树用中序排序那么它输出的结果就是一组有序的数字.
代码实现 :
package demo2;
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public class Solution {
public TreeNode Convert(TreeNode pRootOfTree) {
if (pRootOfTree == null) {
return null;
}
ConvertChild(pRootOfTree);
TreeNode cur = pRootOfTree;
while (cur.left != null) {
cur = cur.left;
}
return cur;
}
TreeNode prev = null;
public void ConvertChild(TreeNode pCur) {
if (pCur == null) {
return;
}
ConvertChild(pCur.left);
pCur.left = prev;
if (prev != null) {
prev.right = pCur;
}
prev = pCur;
ConvertChild(pCur.right);
}
}