资讯专栏INFORMATION COLUMN

[LeetCode] 285. Inorder Successor in BST

focusj / 1599人阅读

Problem

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

Note: If the given node has no in-order successor in the tree, return null.

Example 1:

Input: root = [2,1,3], p = 1

  2
 / 
1   3

Output: 2

Example 2:

Input: root = [5,3,6,2,4,null,null,1], p = 6

      5
     / 
    3   6
   / 
  2   4
 /   
1

Output: null

Solution
class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        //successor must be larger then the node itself, so:
        //if p is in root.left, root can be the successor, null cannot be
        //if p is in root.right, root can not be the successor, null can be
        if (root == null) return null;
        if (root.val <= p.val) {
            return inorderSuccessor(root.right, p);
        } else {
            TreeNode leftRes = inorderSuccessor(root.left, p);
            if (leftRes == null) return root;
            return leftRes;
        }
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72286.html

相关文章

  • LeetCode[285] Inorder Successor in BST

    摘要:复杂度思路找的是比这个大的最小值。代码如果是小于等于的值,就要往右移动比大的值都可能是,所以要保留 LeetCode[285] Inorder Successor in BST Given a binary search tree and a node in it, find the in-order successor of that node in the BST. Note: ...

    oneasp 评论0 收藏0
  • LeetCode 二叉树专项】二叉搜索树中的中序后继(285

    摘要:解法二迭代中序遍历分析作者二叉搜索树的中序后继是中序遍历中当前节点之后最小的节点。 文章目录 1. 题目1.1 示例1.2 说明1.3 限制 2....

    ccj659 评论0 收藏0
  • [Leetcode] Inorder Successor in BST 二叉搜索树中序下一个

    摘要:所以我们要找的上面,实际上是从目标节点向根节点回溯时,第一个比目标节点大的节点。 Inorder Successor in BST Given a binary search tree and a node in it, find the in-order successor of that node in the BST. Note: If the given node has n...

    marek 评论0 收藏0
  • [Leetcode] Binary Search Tree Iterator 二叉搜素树迭代器

    摘要:代码先找到第一个节点,并把路径入栈栈为空时不再有下一个栈顶是待返回元素如果该元素有右节点,把它的右节点及右节点的所有左边节点都压入栈中 Binary Search Tree Iterator 最新更新:https://yanjia.me/zh/2019/02/... Implement an iterator over a binary search tree (BST). Your...

    shixinzhang 评论0 收藏0
  • LeetCode 272 Closest Binary Tree Traversal II 解题思路

    摘要:原题网址题意在二叉搜索树当中找到离最近的个数。解题思路由于二叉搜索数的中序遍历是有序的,比如例子中的树,中序遍历为。 原题网址:https://leetcode.com/problems... Given a non-empty binary search tree and a target value, find k values in the BST that are closes...

    Youngdze 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<