36-二叉搜索树与双向链表
2020-05-06 本文已影响0人
一方乌鸦
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的循环双向链表。要求不能创建任何新的节点,只能调整树中节点指针的指向。
注意审题,看清是否需要循环链表。
生成双向链表模板:
Node pre = null;
Node head = null;
for (...) {
Node tmp = ...;
if (head == null) head = tmp;
if (pre != null) {
pre.right = tmp;
}
tmp.left = pre;
pre = tmp;
}
// 如果需要循环链表
head.left = pre;
pre.right = head;
答案:
/*
// 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 {
Node head;
Node pre;
public Node treeToDoublyList(Node root) {
if (root == null) return null;
recur(root);
head.left = pre;
pre.right = head;
return head;
}
private void recur(Node node) {
if (node == null) return;
recur(node.left);
if (pre != null) {
pre.right = node;
} else {
head = node;
}
node.left = pre;
pre = node;
recur(node.right);
}
}