题解 | #二叉搜索树与双向链表#
二叉搜索树与双向链表
http://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5
中序遍历直接搞定
/**
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 {
public TreeNode Convert(TreeNode pRootOfTree) {
Stack<TreeNode> stack = new Stack<>();
List<Integer> list = new ArrayList<>();
TreeNode node = new TreeNode(0);
TreeNode res = node;
//stack.add(pRootOfTree);
int count=0;
while(stack.empty()==false||pRootOfTree!=null){
while(pRootOfTree!=null){
stack.push(pRootOfTree);
pRootOfTree = pRootOfTree.left;
}
TreeNode temp =stack.pop();
node.right=new TreeNode(temp.val);
if(count>0)node.right.left=node;
node = node.right;
pRootOfTree = temp.right;
count++;
}
return res.right;
}
}