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: nullSolution
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 Given a binary search tree and a node in it, find the in-order successor of that node in the BST. Note: ...
摘要:解法二迭代中序遍历分析作者二叉搜索树的中序后继是中序遍历中当前节点之后最小的节点。 文章目录 1. 题目1.1 示例1.2 说明1.3 限制 2....
摘要:所以我们要找的上面,实际上是从目标节点向根节点回溯时,第一个比目标节点大的节点。 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...
摘要:代码先找到第一个节点,并把路径入栈栈为空时不再有下一个栈顶是待返回元素如果该元素有右节点,把它的右节点及右节点的所有左边节点都压入栈中 Binary Search Tree Iterator 最新更新:https://yanjia.me/zh/2019/02/... Implement an iterator over a binary search tree (BST). Your...
摘要:原题网址题意在二叉搜索树当中找到离最近的个数。解题思路由于二叉搜索数的中序遍历是有序的,比如例子中的树,中序遍历为。 原题网址:https://leetcode.com/problems... Given a non-empty binary search tree and a target value, find k values in the BST that are closes...
阅读 1413·2023-04-26 01:58
阅读 2289·2021-11-04 16:04
阅读 1781·2021-08-31 09:42
阅读 1771·2021-07-25 21:37
阅读 1070·2019-08-30 15:54
阅读 2079·2019-08-30 15:53
阅读 3055·2019-08-29 13:28
阅读 2693·2019-08-29 10:56