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, returnnull. 给一个二叉搜索树和它的一个节点,找出它的中序后继节点,如果没有返回null。 解法1: 用中序遍历二叉搜索树,当找...
若 node 是其 parent 的右子结点时,则将 node 赋值为其 parent,继续向上找,直到其 parent 结点不存在了,此时说明不存在大于 node 值的祖先结点,这说明 node 是 BST 的最后一个结点了,没有后继结点,直接返回 nullptr 即可,参见代码如下: 解法二: classSolution {public: Node* inorderSuccessor(Node*node) {...
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, returnnull. 题解: successor could be自己的parent, or 右子树中最左的点. For both cases, if p.val < root.val, updat...
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 nodepis the node with the smallest key greater thanp.val. Example 1: Input: root = [2,1,3], p = 1 Output: 2 Explanation: 1's in-order successor node is 2...
https://leetcode.com/problems/inorder-successor-in-bst/description/ image.png 这道题如何思考。 我们可以发现,如果根节点的值和P的值一样的时候,下一个值无非就是跟节点右子树的最左端。如果根节点比P大,我们应该去右边找和P一样大的节点。
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, returnnull. Solution 用中序遍历的方式遍历树,这里这个节点的位置有几种可能性: ...
94. 二叉树的中序遍历 - 给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。 示例 1: [https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg] 输入:root = [1,null,2,3] 输出:[1,3,2] 示例 2: 输入:root = [] 输出:[] 示例 3: 输入:ro
TreeNode*left = inorderSuccessor(root->left, p);returnleft ?left : root; } } }; Github 同步地址: https://github.com/grandyang/leetcode/issues/285 类似题目: Binary Search Tree Iterator Binary Tree Inorder Traversal Inorder Successor in BST II ...
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. 本题要求查找p在树中的inorder successor(中序遍历时的下一个节点)。根据p和root的关系,有三种情况。
Given a binary search tree and a node in it, find the in-order successor of that node in the BST. 一刷 题解: 类似于binary search,我们要找一个大于该点的最小值。 /** * Definition for a binary tree node. * public class TreeNode { ...