剑指 Offer 36. 二叉搜索树与双向链表
题目:
思路:
1.链表有序,所以要使用中序遍历
(顺便复习下先序和后续)
2.根节点和左子树的最大值相连,和右子树的最小值相连
3.维持一个head和last,每次递归的时候我们只需要维持尾节点即可,
/*
// 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 {
private Node head = null;
private Node last = null;
public Node treeToDoublyList(Node root) {
if (root == null) {
return null;
}
covert(root);
// 题目要求首尾相连,贼鸡儿坑
head.left = last;
last.right = head;
return head;
}
private void covert(Node root) {
if (root == null) {
return;
}
covert(root.left);
// 中序遍历处理逻辑开始
// 1、中序第一个遇到的必是head
if (head == null) {
head = root;
}
root.left = last;
if (last != null) {
last.right = root;
}
last = root;
// 中序遍历处理逻辑结束
covert(root.right);
}
}