forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecoverbinarysearchtree.java
More file actions
executable file
·45 lines (42 loc) · 1.01 KB
/
recoverbinarysearchtree.java
File metadata and controls
executable file
·45 lines (42 loc) · 1.01 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
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
TreeNode lastNode;
int flag;
TreeNode node1;
TreeNode node2;
public void inorder(TreeNode root){
if(root==null) return;
inorder(root.left);
if(root.val<lastNode.val){
if(flag==0){
node1 = lastNode;
node2 = root;
}else if(flag==1){
node2 = root;
}
flag++;
}
lastNode = root;
inorder(root.right);
}
public void recoverTree(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
lastNode = new TreeNode(Integer.MIN_VALUE);
flag = 0;
node1 = null;
node2 = null;
inorder(root);
int tmp = node1.val;
node1.val = node2.val;
node2.val = tmp;
}
}