@@ -32,35 +32,58 @@ public int kthSmallest(TreeNode root, int k) {
32
32
throw new IllegalStateException ();
33
33
}
34
34
35
- /**
36
- * Morris
37
- */
38
- private int kthSmallest2 (TreeNode root , int k ) {
39
- TreeNode temp ;
35
+ public int kthSmallest2 (TreeNode root , int k ) {
36
+ TreeNodeWithCount rootWithCount = buildTreeWithCount (root );
37
+ return kthSmallest (rootWithCount , k );
38
+ }
40
39
41
- while (root != null ) {
42
- if (root .left == null ) {
43
- if (--k == 0 ) {
44
- return root .val ;
45
- }
46
- root = root .right ;
40
+ public int kthSmallest (TreeNodeWithCount root , int k ) {
41
+ if (root == null ) {
42
+ return -1 ;
43
+ }
44
+
45
+ if (root .left != null ) {
46
+ if (k <= root .left .count ) {
47
+ return kthSmallest (root .left , k );
48
+ } else if (k == root .left .count + 1 ) {
49
+ return root .val ;
47
50
} else {
48
- temp = root .left ;
49
- while (temp .right != null && temp .right != root ) {
50
- temp = temp .right ;
51
- }
52
- if (temp .right == null ) {
53
- temp .right = root ;
54
- root = root .left ;
55
- } else {
56
- temp .right = null ;
57
- if (--k == 0 ) {
58
- return root .val ;
59
- }
60
- root = root .right ;
61
- }
51
+ return kthSmallest (root .right , k - root .left .count - 1 );
62
52
}
63
53
}
64
- throw new IllegalStateException ();
54
+
55
+ if (k == 1 ) {
56
+ return root .val ;
57
+ } else {
58
+ return kthSmallest (root .right , k - 1 );
59
+ }
60
+ }
61
+
62
+ private TreeNodeWithCount buildTreeWithCount (TreeNode root ) {
63
+ if (root == null ) {
64
+ return null ;
65
+ }
66
+ TreeNodeWithCount nroot = new TreeNodeWithCount (root .val );
67
+ nroot .left = buildTreeWithCount (root .left );
68
+ nroot .right = buildTreeWithCount (root .right );
69
+
70
+ if (nroot .left != null ) {
71
+ nroot .count += nroot .left .count ;
72
+ }
73
+
74
+ if (nroot .right != null ) {
75
+ nroot .count += nroot .right .count ;
76
+ }
77
+ return nroot ;
78
+ }
79
+
80
+ class TreeNodeWithCount {
81
+ TreeNodeWithCount left , right ;
82
+ int count , val ;
83
+
84
+ TreeNodeWithCount (int val ) {
85
+ this .val = val ;
86
+ this .count = 1 ;
87
+ }
65
88
}
66
89
}
0 commit comments