Inorder Successor in Binary Search Tree

本文介绍了一种在二叉搜索树中寻找指定节点的中序后继节点的方法。提供了两种解决方案:一种利用节点右子树的最小值作为后继;另一种通过递归遍历整棵树找到目标节点的后继。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 1 public class Solution {
 2 
 3     public TreeNode inorderSuccessor(TreeNode root, TreeNode n) {
 4         if (root == null) return null;
 5 
 6         if (n.right != null) {
 7             return min(n.right);
 8         }
 9 
10         TreeNode succ = null;
11         while (root != null) {
12             if (n.val < root.val) { //左子树的successor都是当前树的root。
13                 succ = root;
14                 root = root.left;
15             } else if (n.val > root.val)
16                 root = root.right;
17             else
18                 break;
19         }
20         return succ;
21     }
22 
23     public TreeNode min(TreeNode n) {
24         if (n.left != null) {
25             return min(n.left);
26         }
27         return n;
28     }
29 }
30 
31 class TreeNode {
32     TreeNode left;
33     TreeNode right;
34     int val;
35 
36     public TreeNode(int i) {
37         val = i;
38     }
39 }

 Another solution

 1 public class Solution {
 2     TreeNode pre = null;
 3     TreeNode succ = null;
 4 
 5     void inorderSuccessorII(TreeNode root, TreeNode p) {
 6         if (root == null || succ != null)
 7             return;
 8         inorderSuccessor(root.left, p);
 9         if (pre == p) {
10             succ = root;
11         }
12         pre = root;
13         inorderSuccessor(root.right, p);
14     }
15 }

 

转载于:https://www.cnblogs.com/beiyeqingteng/p/5745222.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值