Advertisement
Guest User

Untitled

a guest
Feb 13th, 2016
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1.  
  2. 其实很简单,successor上来为null。如果p在root左边,就动successor=root,右边就不动,直到root为null。
  3. public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
  4. TreeNode succ = null;
  5. while (root != null) {
  6. if (p.val < root.val) {
  7. succ = root;
  8. root = root.left;
  9. }
  10. else
  11. root = root.right;
  12. }
  13. return succ;
  14. }
  15. ----分割线
  16. public class Solution {
  17. private TreeNode dummy = new TreeNode(-1);
  18. public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
  19. if (root == null) {
  20. return root;
  21. }
  22. if (p == null) {
  23. return p;
  24. }
  25. // write your code here
  26. TreeNode firstRightAncestor = dummy;
  27. TreeNode parent = dummy;
  28. return successorHelper(root, p, firstRightAncestor, parent);
  29. }
  30. private TreeNode successorHelper(TreeNode root, TreeNode p,
  31. TreeNode firstRightAncestor, TreeNode parent) {
  32. if (root == null) {
  33. return null;
  34. }
  35. if (root == p) {
  36. if (p.right != null) {
  37. // p has a right subtree
  38. return findSmallest(root.right);
  39. } else if (parent == dummy) {
  40. // p doesn't have any ancestor
  41. return null;
  42. } else if (parent.right == p) {
  43. return firstRightAncestor == dummy ? null : firstRightAncestor;
  44. }
  45. return parent;
  46. }
  47. parent = root;
  48. // update firstRightAncestor
  49. if (p.val < root.val) {
  50. firstRightAncestor = root;
  51. root = root.left;
  52. } else {
  53. root = root.right;
  54. }
  55. return successorHelper(root, p, firstRightAncestor, parent);
  56. }
  57. private TreeNode findSmallest(TreeNode root) {
  58. return root.left == null ? root : findSmallest(root.left);
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement