LC 897. 递增顺序搜索树

题目描述

这是 LeetCode 上的 897. 递增顺序搜索树 ,难度为 简单

给你一棵二叉搜索树,请你 按中序遍历 将其重新排列为一棵递增顺序搜索树,使树中最左边的节点成为树的根节点,并且每个节点没有左子节点,只有一个右子节点。

示例 1:

1
2
3
输入:root = [5,3,6,2,4,null,8,1,null,null,null,7,9]

输出:[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]

示例 2:

1
2
3
输入:root = [5,1,7]

输出:[1,null,5,null,7]

提示:

  • 树中节点数的取值范围是 [1, 100]
  • 0 <= Node.val <= 1000

基本思路

由于给定的树是一棵「二叉搜索树」,因此只要对其进行「中序遍历」即可得到有序列表,再根据有序列表构建答案即可。

而二叉搜索树的「中序遍历」有「迭代」和「递归」两种形式。


递归

递归写法十分简单,属于树的遍历中最简单的实现方式。

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
List<TreeNode> list = new ArrayList<>();
public TreeNode increasingBST(TreeNode root) {
dfs(root);
TreeNode dummy = new TreeNode(-1);
TreeNode cur = dummy;
for (TreeNode node : list) {
cur.right = node;
node.left = null;
cur = node;
}
return dummy.right;
}
void dfs(TreeNode root) {
if (root == null) return ;
dfs(root.left);
list.add(root);
dfs(root.right);
}
}

  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$

迭代

迭代其实就是使用「栈」来模拟递归过程,也属于树的遍历中的常见实现形式。

一般简单的面试中如果问到树的遍历,面试官都不会对「递归」解法感到满意,因此掌握「迭代/非递归」写法同样重要。

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
List<TreeNode> list = new ArrayList<>();
public TreeNode increasingBST(TreeNode root) {
Deque<TreeNode> d = new ArrayDeque<>();
while (root != null || !d.isEmpty()) {
while (root != null) {
d.add(root);
root = root.left;
}
root = d.pollLast();
list.add(root);
root = root.right;
}
TreeNode dummy = new TreeNode(-1);
TreeNode cur = dummy;
for (TreeNode node : list) {
cur.right = node;
node.left = null;
cur = node;
}
return dummy.right;
}
}

  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$

最后

这是我们「刷穿 LeetCode」系列文章的第 No.897 篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。

在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。

为了方便各位同学能够电脑上进行调试和提交代码,我建立了相关的仓库:https://github.com/SharingSource/LogicStack-LeetCode

在仓库地址里,你可以看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其他优选题解。