File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments