Guest User

Untitled

a guest
Jun 24th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. using System;
  2.  
  3. class Solution
  4. {
  5. public class Node
  6. {
  7. public int value;
  8. public Node left;
  9. public Node right;
  10. public Node parent;
  11. }
  12.  
  13. public static Node findInOrderSuccessor(Node inputNode)
  14. {
  15. if(inputNode == null)
  16. return null;
  17.  
  18. if(inputNode.right != null)
  19. {
  20. // find leftmost node in right subtree
  21. return findLeftMostNode(inputNode.right);
  22. }
  23. else
  24. {
  25. var iterate = inputNode;
  26. while(iterate.parent != null && iterate.parent < inputNode.value)
  27. {
  28. iterate = iterate.parent;
  29. }
  30.  
  31. return iterate.parent;
  32. }
  33. }
  34.  
  35. private static Node findLeftMostNode(Node root)
  36. {
  37. var iterate = root;
  38. while(iterate.left != null)
  39. iterate = iterate.left;
  40.  
  41. return iterate;
  42. }
  43.  
  44. static void Main(string[] args)
  45. {
  46. // test findInOrderSuccessor here
  47. }
  48. }
  49. // keywords: BST, inorder successor,
  50. // given a node inputNode in a BST, asking: inorder successor
  51. // in other words, bigger, smallest one in all bigger elements
  52.  
  53. // brute force, inorder traversal -> 5, 9, 11, 12, 14, 20, 25, given node 9, search the array to find 9, next element - O(n)
  54. // try to do O(logn), try to start from given node, back to root node or down to leaf node, try to find successor
Add Comment
Please, Sign In to add comment