中序遍歷择膝,但是記住要保存前一個節(jié)點的指針坯屿,因此要用到指針的指針作為參數(shù)油湖。
同時,因為最后要返回頭指針领跛,不要把返回頭指針這件事情也放在一起乏德,寫代碼起來才比較方便。
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;
}
}