# 《剑指Offer》36：二叉搜索树与双向链表

## 题目

public static class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}


## 放码

import com.lun.util.BinaryTree.TreeNode;

private TreeNode last;//用于指向双向链表的尾节点

public TreeNode convert(TreeNode root) {
convertNode(root);

}
}

private void convertNode(TreeNode node) {

if(node == null) {
return;
}

TreeNode current = node;

if(current.left != null) {
convertNode(current.left);
}

current.left = last;//1.执行到这步，左子树已经转换成有序双向链表

if(last != null) {
last.right = current;//2.
}

last = current;//3.current转换成有序双向链表的新尾节点

if(current.right != null) {
convertNode(current.right);
}
}

}


## 测试

import org.junit.Assert;
import org.junit.Test;

import com.lun.util.BinaryTree;
import com.lun.util.BinaryTree.TreeNode;

@Test
public void test() {
TreeNode root = makeABST();
Assert.assertEquals("4 -> 6 -> 8 -> 10 -> 12 -> 14 -> 16 -> \n" +
"16 -> 14 -> 12 -> 10 -> 8 -> 6 -> 4 -> ", printList(head));
}

private TreeNode makeABST() {
int[] array = {10, 6, 14, 4, 8, 12, 16};
return BinaryTree.integerArray2BinarySearchTree(array);
}

String result = "";

while(true) {
result += (p.val + " -> ");

if(p.right == null) {
break;
}
p = p.right;
}

result += "\n";

while(p != null) {
result = result +  p.val + " -> ";
p = p.left;
}
return result;
}

}


• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

巨輪

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
06-04 1315

02-09 156
02-19 50
03-10 264
03-18 330
02-20 422
04-24