Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 其实很简单,successor上来为null。如果p在root左边,就动successor=root,右边就不动,直到root为null。
- public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
- TreeNode succ = null;
- while (root != null) {
- if (p.val < root.val) {
- succ = root;
- root = root.left;
- }
- else
- root = root.right;
- }
- return succ;
- }
- ----分割线
- public class Solution {
- private TreeNode dummy = new TreeNode(-1);
- public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
- if (root == null) {
- return root;
- }
- if (p == null) {
- return p;
- }
- // write your code here
- TreeNode firstRightAncestor = dummy;
- TreeNode parent = dummy;
- return successorHelper(root, p, firstRightAncestor, parent);
- }
- private TreeNode successorHelper(TreeNode root, TreeNode p,
- TreeNode firstRightAncestor, TreeNode parent) {
- if (root == null) {
- return null;
- }
- if (root == p) {
- if (p.right != null) {
- // p has a right subtree
- return findSmallest(root.right);
- } else if (parent == dummy) {
- // p doesn't have any ancestor
- return null;
- } else if (parent.right == p) {
- return firstRightAncestor == dummy ? null : firstRightAncestor;
- }
- return parent;
- }
- parent = root;
- // update firstRightAncestor
- if (p.val < root.val) {
- firstRightAncestor = root;
- root = root.left;
- } else {
- root = root.right;
- }
- return successorHelper(root, p, firstRightAncestor, parent);
- }
- private TreeNode findSmallest(TreeNode root) {
- return root.left == null ? root : findSmallest(root.left);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement