-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecoverBST.java
More file actions
47 lines (46 loc) · 1.33 KB
/
recoverBST.java
File metadata and controls
47 lines (46 loc) · 1.33 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
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
ArrayList<TreeNode> t;
TreeNode previous;
public void recoverTree(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
t = new ArrayList<TreeNode>();
previous=null;
inorder(root);
int temp = t.get(0).val;
t.get(0).val = t.get(t.size()-1).val;
t.get(t.size()-1).val = temp;
//被换的恰好在头和尾
}
public void inorder(TreeNode root) {
if(root==null) return;
inorder(root.left);
if(previous!=null&&previous.val>root.val) {
if(!t.contains(previous)) t.add(previous); //no need contains
if(!t.contains(root)) t.add(root);
}
previous = root;
inorder(root.right);
}
}
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
// Start typing your Java solution below
// DO NOT write main() function
if (p == null)
return q == null;
else if (q == null)
return false;
else
return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}