First, we use recursive way.

Successor

 1 public class Solution {
 2     public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
 3         if (root == null) {
 4             return null;
 5         }
 6         if (root.val <= p.val) {
 7             return inorderSuccessor(root.right, p);
 8         } else {
 9             TreeNode left = inorderSuccessor(root.left, p);
10             return left == null ? root : left;
11         }
12     }
13 }

Predecessor

 1 public class Solution {
 2     public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
 3         if (root == null) {
 4             return null;
 5         }
 6         if (root.val >= p.val) {
 7             return inorderSuccessor(root.left, p);
 8         } else {
 9             TreeNode right = inorderSuccessor(root.right, p);
10             return right == null ? root : right;
11         }
12     }
13 }

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-28
  • 2021-09-25
  • 2022-12-23
  • 2021-09-18
猜你喜欢
  • 2021-11-29
  • 2021-06-09
  • 2021-06-19
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案