算法记录
LeetCode 题目:
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的循环双向链表。
说明
一、题目
要求不能创建任何新的节点,只能调整树中节点指针的指向。
二、分析
- 二叉树的两个子树恰好就能标识双向链表的两个方向,而二叉搜索树的中序遍历刚好就是一条有序链表。
- 只要在遍历的同时改变指向即可。
class Solution {
private Node pre;
private Node next;
public Node treeToDoublyList(Node root) {
if(root == null) return null;
pre = null;
next = null;
dfs(root);
pre.left = next;
next.right = pre;
return pre;
}
public void dfs(Node root) {
if(root == null) return ;
dfs(root.left);
if(next == null) pre = root;
else next.right = root;
root.left = next;
next = root;
dfs(root.right);
}
}
总结
熟悉二叉搜索树的节点结构和特点。