Inorder Successor in BST Solutions in Java
Number 285
Difficulty Medium
Acceptance 40.5%
Link LeetCode
Other languages —
Solutions
Java solution by haoel/leetcode
// Source : http://www.lintcode.com/en/problem/inorder-successor-in-bst/// https://leetcode.com/problems/inorder-successor-in-bst/// Inspired by : http://www.jiuzhang.com/solutions/inorder-successor-in-bst/// Author : Lei Cao// Date : 2015-10-06package inorderSuccessorInBST;public class inorderSuccessorInBST {public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {TreeNode successor = null;if (root == null) {return null;}while (root != null && root.val != p.val) {if (root.val > p.val) {successor = root;root = root.left;} else {root = root.right;}}if (root == null) {return null;}if (root.right == null) {return successor;}root = root.right;while (root.left != null) {root = root.left;}return root;}}