-
-
Notifications
You must be signed in to change notification settings - Fork 297
/
Copy path897.java
61 lines (57 loc) · 1.85 KB
/
897.java
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
50
51
52
53
54
55
56
57
58
59
60
61
__________________________________________________________________________________________________
sample 1 ms submission
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
TreeNode prev = null, head = null;
public TreeNode increasingBST(TreeNode root) {
if(root==null) return null;
increasingBST(root.left);
if(prev!=null) {
root.left=null; // we no longer needs the left side of the node, so set it to null
prev.right=root;
}
if(head==null) head=root; // record the most left node as it will be our root
prev=root; //keep track of the prev node
increasingBST(root.right);
return head;
}
}
__________________________________________________________________________________________________
sample 38260 kb submission
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode increasingBST(TreeNode root) {
List<Integer> vals = new ArrayList();
thePostOrderTraversal(root, vals);
// result.val = vals.get(0);
TreeNode ans = new TreeNode(0), cur = ans;
for (int v: vals) {
cur.right = new TreeNode(v);
cur = cur.right;
}
return ans.right;
}
public void thePostOrderTraversal(TreeNode root,List<Integer> list) {
if (root == null) return;
thePostOrderTraversal(root.left, list);
list.add(root.val);
thePostOrderTraversal(root.right, list);
}
}
__________________________________________________________________________________________________