剑指offer之 二叉搜索树与双向链表
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 pRootOfTree;
//TreeNode pLastOfList = null;
TreeNode pLastOfList = new TreeNode(0);
pLastOfList = ConvertNode(pRootOfTree, pLastOfList);
TreeNode pHeadOfList = pLastOfList;
while (pLastOfList!=null && pHeadOfList.left!=null) {
pHeadOfList = pHeadOfList.left;
}
pHeadOfList = pHeadOfList.right;
pHeadOfList.left = null;
return pHeadOfList;
}
public TreeNode ConvertNode (TreeNode pNode, TreeNode pLastOfList) {
if (pNode == null)
return pNode;
TreeNode pCurrent = pNode;
if (pCurrent.left != null)
pLastOfList = ConvertNode(pCurrent.left, pLastOfList);
pCurrent.left = pLastOfList;
if (pLastOfList != null)
pLastOfList.right = pCurrent;
pLastOfList = pCurrent;
if (pCurrent.right != null) {
pLastOfList = ConvertNode(pCurrent.right, pLastOfList);
}
return pLastOfList;
}