个人博客:小景哥哥
26.二叉搜索树与双向链表
题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
(也就是说只能创建引用,来调整链表的指向)
解题思路:
1.将左子树构造成双链表,并返回链表头节点。
2.新增一个全局变量记录左子树的最后一个节点。
3.如果左子树链表不为空的话,将当前root追加到左子树链表。
4.将右子树构造成双链表,并返回链表头节点。
5.如果右子树链表不为空的话,将该链表追加到root节点之后。
6.根据左子树链表是否为空确定返回的节点。
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public class Solution {
protected TreeNode lastLeft = null;
public TreeNode Convert(TreeNode root) {
if(root == null)
return null;
if(root.left == null && root.right == null){
lastLeft = root;
return root;
}
TreeNode left = Convert(root.left);
if(lastLeft != null){
lastLeft.right = root;
root.left = lastLeft;
}
lastLeft = root;
TreeNode right = Convert(root.right);
if(right != null){
root.right = right;
right.left = root;
}
return left != null? left:root;
}
}