Skip to content

Commit d7b850c

Browse files
committed
Sync LeetCode submission Runtime - 62 ms (24.45%), Memory - 21 MB (41.74%)
1 parent 25690c9 commit d7b850c

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<p>Given the <code>root</code> of a binary search tree and a node <code>p</code> in it, return <em>the in-order successor of that node in the BST</em>. If the given node has no in-order successor in the tree, return <code>null</code>.</p>
2+
3+
<p>The successor of a node <code>p</code> is the node with the smallest key greater than <code>p.val</code>.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
<img alt="" src="https://assets.leetcode.com/uploads/2019/01/23/285_example_1.PNG" style="width: 122px; height: 117px;" />
8+
<pre>
9+
<strong>Input:</strong> root = [2,1,3], p = 1
10+
<strong>Output:</strong> 2
11+
<strong>Explanation:</strong> 1&#39;s in-order successor node is 2. Note that both p and the return value is of TreeNode type.
12+
</pre>
13+
14+
<p><strong class="example">Example 2:</strong></p>
15+
<img alt="" src="https://assets.leetcode.com/uploads/2019/01/23/285_example_2.PNG" style="width: 246px; height: 229px;" />
16+
<pre>
17+
<strong>Input:</strong> root = [5,3,6,2,4,null,null,1], p = 6
18+
<strong>Output:</strong> null
19+
<strong>Explanation:</strong> There is no in-order successor of the current node, so the answer is <code>null</code>.
20+
</pre>
21+
22+
<p>&nbsp;</p>
23+
<p><strong>Constraints:</strong></p>
24+
25+
<ul>
26+
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
27+
<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>
28+
<li>All Nodes will have unique values.</li>
29+
</ul>
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Approach 2: Using BST properties
2+
3+
# Time: O(n)
4+
# Space: O(1)
5+
6+
# Definition for a binary tree node.
7+
# class TreeNode:
8+
# def __init__(self, x):
9+
# self.val = x
10+
# self.left = None
11+
# self.right = None
12+
13+
class Solution:
14+
def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> Optional[TreeNode]:
15+
successor = None
16+
17+
while root:
18+
if p.val >= root.val:
19+
root = root.right
20+
else:
21+
successor = root
22+
root = root.left
23+
24+
return successor

0 commit comments

Comments
 (0)