中序遍历,但是记住要保存前一个节点的指针,因此要用到指针的指针作为参数。
同时,因为最后要返回头指针,不要把返回头指针这件事情也放在一起,写代码起来才比较方便。
public static void toOrderedBidirectLink(BinaryTreeNode root){
if(root==null) {
return;
}
BinaryTreeNode lastNode = toOrderedBidirectLink2(root, null);
BinaryTreeNode node = lastNode;
while(node.leftNode!=null)
node = node.leftNode;
return node;
}
private static BinaryTreeNode toOrderedBidirectLink2(BinaryTreeNode root, BinaryTreeNode lastNodeInList) {
if(root.leftNode!=null) {
lastNodeInList = toOrderedBidirectLink2(root.leftNode, lastNodeInList);
}
if(lastNodeInList==null) {
lastNodeInList = root;
lastNodeInList.leftNode = null;
} else {
lastNodeInList.rightNode = root;
root.leftNode = lastNodeInList;
}
if(root.rightNode!=null) {
return toOrderedBidirectLink2(root.rightNode, root);
}else {
return root;
}
}