步骤:
1.找链表的首节点----就是树中最小的节点---->最小的节点就是树中最左侧节点。
2.按照中序遍历的规则来修改每个节点左右孩子的指向。
分析:每拿到- -个节点—只能修改当前节点的左指针域–原因:因为按照中序规则进行遍历,肯定知道当前节点的前一个节点是那个节点(因为其前一个节点刚刚遍历过),当前节点的后序还没有遍历。
public class BSTree {
public static class BSTNode{
BSTNode left = null;
BSTNode right = null;
int val;
BSTNode(int val){
this.val = val;
}
}
private BSTNode root = null;
BSTNode prev = null;//标记中序遍历刚刚遍历过的节点。
public BSTNode BSTree2DList(){
if (null == root){
return null;
}
//1.找树中最左侧的节点,即双向链表的头
BSTNode head = root;
while (null != head.left){
head = head.left;
}
//2.修改每个节点left和right的指向
BSTree2DList(root);
return head;
}
public void BSTree2DList(BSTNode root){
if (null == root){
return;
}
//转化根节点的左子树
BSTree2DList(root.left);
//转化根节点
root.left = prev;
if (null != prev){
prev.right = root;
}
//用prev将刚刚遍历的节点保存起来。
prev = root;
BSTree2DList(root.right);
}
public static void TestBSTree2(){
int[] array = {5,3,4,1,7,8,2,6,0,9};
BSTree t = new BSTree();
for (int e:array){
t.put(e);
}
BSTNode head = t.BSTree2DList();
BSTNode cur = head;
while (cur!=null){
System.out.print(cur.val + "----->");
cur = cur.right;
}
System.out.println("NULL");
}
public static void main(String[] args) {
TestBSTree2();
}
}
/*
打印结果:
0----->1----->2----->3----->4----->5----->6----->7----->8----->9----->NULL
*/