2
2
3
3
import com .fishercoder .common .classes .TreeNode ;
4
4
5
+ import java .util .ArrayList ;
5
6
import java .util .Iterator ;
7
+ import java .util .List ;
6
8
import java .util .Map ;
7
9
import java .util .TreeMap ;
8
10
@@ -17,7 +19,7 @@ public static class Solution1 {
17
19
* <p>
18
20
* The time complexity should be O(h) where h is the depth of the result node.
19
21
* succ is a pointer that keeps the possible successor.
20
- * Whenever you go left the current root is the new possible successor, otherwise the it remains the same.
22
+ * Whenever you go left the current root is the new possible successor, otherwise it remains the same.
21
23
* <p>
22
24
* Only in a balanced BST O(h) = O(log n). In the worst case h can be as large as n.
23
25
*/
@@ -64,4 +66,31 @@ private void inorderTraversal(TreeNode root, TreeMap<Integer, TreeNode> map) {
64
66
}
65
67
}
66
68
69
+ public static class Solution3 {
70
+ public TreeNode inorderSuccessor (TreeNode root , TreeNode p ) {
71
+ List <TreeNode > inorder = new ArrayList <>();
72
+ dfs (root , inorder );
73
+ for (int i = 0 ; i < inorder .size () - 1 ; i ++) {
74
+ if (inorder .get (i ) == p ) {
75
+ return inorder .get (i + 1 );
76
+ }
77
+ }
78
+ return null ;
79
+ }
80
+
81
+ private List <TreeNode > dfs (TreeNode root , List <TreeNode > inorder ) {
82
+ if (root == null ) {
83
+ return inorder ;
84
+ }
85
+ if (root .left != null ) {
86
+ dfs (root .left , inorder );
87
+ }
88
+ inorder .add (root );
89
+ if (root .right != null ) {
90
+ dfs (root .right , inorder );
91
+ }
92
+ return inorder ;
93
+ }
94
+ }
95
+
67
96
}
0 commit comments