1. 题目
2. 题解
/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val,Node _left,Node _right) {
val = _val;
left = _left;
right = _right;
}
};
*/
class Solution {
//把每个结点的left看作双向链表里的pre,right看作双向链表里的next,更容易理解
Node head = null;
Node pre = null;
public Node treeToDoublyList(Node root) {
if (root == null)
return null;
travel(root);
//中序遍历处理过后只是形成了一个双向链表
//让头结点的pre指向尾结点,尾结点的next指向头,才形成循环
head.left = pre;
pre.right = head;
return head;
}
//其实就是一个中序遍历
public void travel(Node root) {
if (root == null)
return;
travel(root.left); //往左走到最里面
//如果头结点为空,说明这是双向链表里的第一个结点
//对头结点只需要处理它的next指针,也就是root.left = pre;
if (head == null) {
head = root;
} else {
//不为头结点时不仅需要处理它自身的next指针(root.left = pre)
//还需要让链表前一结点的next指向当前节点,也就是pre.right = root;
pre.right = root;
}
root.left = pre;
pre = root;
travel(root.right);
}
}