-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIncreasingOrderSearchTree.java
More file actions
49 lines (44 loc) · 1.27 KB
/
Copy pathIncreasingOrderSearchTree.java
File metadata and controls
49 lines (44 loc) · 1.27 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
// This solution needs to traverse the left subtree everytime we need to combine the result.
// So it might get slow
class Solution {
public TreeNode increasingBST(TreeNode root) {
if(root == null) return root;
if(root.left == null && root.right == null) return root;
if(root.right != null) root.right = increasingBST(root.right);
if(root.left != null) {
TreeNode left = increasingBST(root.left);
TreeNode p = left;
while(p.right != null) p = p.right;
p.right = root;
return left;
} else {
return root;
}
}
}
// In order traverse solution
class Solution {
private final TreeNode dummy = new TreeNode(0);
private TreeNode p = dummy;
public TreeNode increasingBST(TreeNode root) {
inorder(root);
return dummy.right;
}
private void inorder(TreeNode root) {
if(root == null) return;
inorder(root.left);
p.right = root;
root.left = null;
p = p.right;
inorder(root.right);
}
}