Sword refers to offer 36. Binary search tree and doubly linked list
Title description
Problem-solving ideas
The in-order traversal of the binary search tree is the sequential linked list.
This question also uses the method of in-order traversal of the record predecessor .
class Solution {
Node head, pre;
public Node treeToDoublyList(Node root) {
if (root == null) return null;
//将树转化为双向链表,pre最后停留在尾节点上
inorderTraversal(root);
//将 双向链表 转化为 双向循环链表
head.left = pre;
pre.right = head;
return head;
}
//中序遍历,将以root为根节点的树转化为双向链表
public void inorderTraversal(Node root) {
if (root == null) return;
inorderTraversal(root.left);
if (pre != null) {
pre.right = root;
} else {
head = root; //双向链表的头结点
}
root.left = pre;
pre = root; //记录前驱
inorderTraversal(root.right);
}
}