题解 | #将二叉搜索树变为双向链表#
二叉搜索树与双向链表
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;
}
} */ public class Solution {
public 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);
}
public TreeNode Convert(TreeNode pRootOfTree) {
if(pRootOfTree ==null) return null;
ConvertChild(pRootOfTree);
//找到链表的头节点
TreeNode head=pRootOfTree;
while(head.left !=null){
head=head.left;
}
return head;
}
}