Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3865230

Browse files
committed
20190508
1 parent 9e6859a commit 3865230

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

‎code/lc99.java

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package code;
2+
3+
import java.util.Stack;
4+
/*
5+
* 99. Recover Binary Search Tree
6+
* 题意:二叉搜索树中两个节点错位了,恢复二叉搜索树,用O(1)空间
7+
* 难度:Hard
8+
* 分类:Tree, Depth-first Search
9+
* 思路:只要记录错乱的节点就可以了,最后交换两个节点的值
10+
* 先序遍历 在print那个地方加上逻辑代码
11+
* Tips:
12+
*/
13+
public class lc99 {
14+
public class TreeNode {
15+
int val;
16+
TreeNode left;
17+
TreeNode right;
18+
TreeNode(int x) {
19+
val = x;
20+
}
21+
}
22+
23+
TreeNode tn1 = null;
24+
TreeNode tn2 = null;
25+
public void recoverTree(TreeNode root) {
26+
inorder(root);
27+
int temp = tn1.val;
28+
tn1.val = tn2.val;
29+
tn2.val = temp;
30+
}
31+
32+
public void inorder(TreeNode root){
33+
TreeNode pre = null;
34+
Stack<TreeNode> st = new Stack();
35+
while(root!=null || !st.isEmpty()){
36+
while(root!=null){
37+
st.add(root);
38+
root = root.left;
39+
}
40+
root = st.pop();
41+
if(pre!=null && pre.val>root.val && tn1==null)
42+
tn1 = pre;
43+
if(pre!=null && pre.val>root.val && tn1!=null) //可能被执行多次 eg 3 2 1 tn2 先被赋值2 后被赋值1
44+
tn2 = root;
45+
pre = root;
46+
root = root.right;
47+
}
48+
}
49+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /