-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInorderSuccessorInBST.java
More file actions
54 lines (44 loc) · 1.26 KB
/
InorderSuccessorInBST.java
File metadata and controls
54 lines (44 loc) · 1.26 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
46
47
48
49
50
51
52
53
54
package Leetcode;
import java.util.List;
import java.util.Stack;
public class InorderSuccessorInBST
{
public TreeNode inorderSuccessor( TreeNode root, TreeNode p )
{
if(root==null || p==null)
return null;
if(p.right!=null)
{
TreeNode temp = p.right;
while(temp.left!=null)
{
temp= temp.left;
}
return temp;
}
Stack<TreeNode> stack = new Stack();
int inorder = Integer.MIN_VALUE;
TreeNode temp = root;
while(temp!=null || !stack.isEmpty())
{
while(temp!=null)
{
stack.push( temp );
temp = temp.left;
}
temp = stack.pop();
if(inorder==p.val) return temp;
inorder = temp.val;
temp= temp.right;
}
return null;
}
public static void main( String[] args )
{
TreeNode root = new TreeNode(2 );
root.left = new TreeNode(1);
root.right = new TreeNode(3);
InorderSuccessorInBST obj = new InorderSuccessorInBST();
System.out.println( obj.inorderSuccessor( root, root.left ).val );
}
}