首页 > 其他 > 详细

[LC] 285. Inorder Successor in BST

时间:2020-01-30 12:46:55      阅读:70      评论:0      收藏:0      [点我收藏+]

Given a binary search tree and a node in it, find the in-order successor of that node in the BST.

The successor of a node p is the node with the smallest key greater than p.val.

 

Example 1:

技术分享图片

Input: root = [2,1,3], p = 1
Output: 2
Explanation: 1‘s in-order successor node is 2. Note that both p and the return value is of TreeNode type.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        TreeNode res = null;
        while (root != null) {
            if (root.val <= p.val) {
                root = root.right;
            } else {
                // only when p.val < root, root can possibly be the successor, continue check root.left
                res = root;
                root = root.left;
            }
        }
        return res;
    }
}

 

Good Reference: https://leetcode.com/problems/inorder-successor-in-bst/discuss/72653/Share-my-Java-recursive-solution

[LC] 285. Inorder Successor in BST

原文:https://www.cnblogs.com/xuanlu/p/12242399.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!