Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. class Solution {
  2. public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
  3. // the successor is somewhere lower in the right subtree
  4. // successor: one step right and then left till you can
  5. if (p.right != null) {
  6. p = p.right;
  7. while (p.left != null) p = p.left;
  8. return p;
  9. }
  10.  
  11. // the successor is somewhere upper in the tree
  12. ArrayDeque<TreeNode> stack = new ArrayDeque<>();
  13. int inorder = Integer.MIN_VALUE;
  14.  
  15. // inorder traversal : left -> node -> right
  16. while (!stack.isEmpty() || root != null) {
  17. // 1. go left till you can
  18. while (root != null) {
  19. stack.push(root);
  20. root = root.left;
  21. }
  22.  
  23. // 2. all logic around the node
  24. root = stack.pop();
  25. // if the previous node was equal to p
  26. // then the current node is its successor
  27. if (inorder == p.val) return root;
  28. inorder = root.val;
  29.  
  30. // 3. go one step right
  31. root = root.right;
  32. }
  33.  
  34. // there is no successor
  35. return null;
  36. }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement