LC.P897[递增顺序搜索树]

方法一:DFS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode increasingBST(TreeNode root) {
List<TreeNode> list = new ArrayList<>();
inOrder(root, list);
TreeNode ans = new TreeNode(-1), p = ans;
for (TreeNode node : list) {
p.right = node;
p = node;
}
return ans.right;
}

private void inOrder(TreeNode root, List<TreeNode> list) {
if (root == null) return;
inOrder(root.left, list);
list.add(new TreeNode(root.val));
inOrder(root.right, list);
}
}
  • 时间复杂度:$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
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode increasingBST(TreeNode root) {
List<TreeNode> list = new ArrayList<>();
Deque<TreeNode> stack = new ArrayDeque<>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
list.add(root);
root = root.right;
}
TreeNode ans = new TreeNode(-1), p = ans;
for (TreeNode node : list) {
p.right = node;
node.left = null;
p = node;
}
return ans.right;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$