注:此博客不再更新,所有最新文章将发表在个人独立博客limengting.site。分享技术,记录生活,欢迎大家关注
题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
方法一:非递归版
解题思路:
1.核心是中序遍历的非递归算法。
2.修改当前遍历节点与前一遍历节点的指针指向。
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.Stack;
public class Solution {
public TreeNode Convert(TreeNode root) {
if (root == null) return null;
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
TreeNode pre = null;
boolean isHead = true;
while (cur != null || !stack.isEmpty()) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
// pre = null
// cur = first node of in-order sequence
if (isHead) {
root = cur; // set first node of in-order sequence to root
isHead = false;
} else {
pre.right = cur;
cur.left = pre;
}
pre = cur;
cur = cur.right;
}
return root;
}
}
方法二:递归
解题思路:
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 {
public TreeNode Convert(TreeNode root) {
if (root == null) return null;
if (root.left == null && root.right == null) {
return root;
}
//1.将左子树构造成双链表,并返回链表头节点。
TreeNode left = Convert(root.left);
TreeNode cur = left;
//2.定位至左子树双链表最后一个节点。
while (cur != null && cur.right != null) {
cur = cur.right;
}
//3.如果左子树链表不为空的话,将当前root追加到左子树链表。
if (left != null) {
cur.right = root;
root.left = cur;
}
//4.将右子树构造成双链表,并返回链表头节点。
TreeNode right = Convert(root.right);
//5.如果右子树链表不为空的话,将该链表追加到root节点之后。
if (right != null) {
right.left = root;
root.right = right;
}
//6.根据左子树链表是否为空确定返回的节点。
return left == null ? root : left;
}
}