题解 | 二叉搜索树与双向链表
二叉搜索树与双向链表
https://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5
import java.util.*;
/**
public 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) {
List<TreeNode> list = new ArrayList<>();
toConvert(pRootOfTree, list);
if (list.isEmpty()) return null;
TreeNode lastNode = list.get(0);
for (int i = 1; i < list.size(); i++) {
TreeNode currentNode = list.get(i);
lastNode.right = currentNode;
currentNode.left = lastNode;
lastNode = currentNode;
}
return list.get(0);
}
static public void toConvert(TreeNode pRootOfTree, List<TreeNode> list) {
if (pRootOfTree == null) {
return;
}
if (pRootOfTree.left != null) {
toConvert(pRootOfTree.left, list);
}
list.add(pRootOfTree);
if (pRootOfTree.right != null) {
toConvert(pRootOfTree.right, list);
}
}
}
