题解 | #二叉搜索树与双向链表#
二叉搜索树与双向链表
http://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5
开辟一个数组存储节点然后依次向下指但是空间复杂度为O(n),不满足题意、。。。。。。
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.*;
public class Solution {
ArrayList<TreeNode> we = new ArrayList<>();
public TreeNode Convert(TreeNode pRootOfTree) {
deep(pRootOfTree);
System.out.print(we.size());
if(pRootOfTree == null || (pRootOfTree.left == null && pRootOfTree.right == null)){
return pRootOfTree;
}
for(int i=0;i<we.size();i++){
if(i == 0){
we.get(i).left = null;
we.get(i).right = we.get(i+1);
}
else if(i == we.size() - 1){
we.get(i).left = we.get(i-1);
we.get(i).right = null;
}
else{
we.get(i).left = we.get(i-1);
we.get(i).right = we.get(i+1);
}
}
return we.get(0);
}
public TreeNode deep(TreeNode pRootOfTree){
if(pRootOfTree == null){
return null;
}
deep(pRootOfTree.left);
we.add(pRootOfTree);
deep(pRootOfTree.right);
return null;
}
}