求二叉搜索树的中序后继节点
分析:
1. 如果目标节点的右子树不为空,则返回右子树的最小节点;
2. 如果目标节点的右子树为空,则从根节点开始遍历。
实现代码如下:
1 public class Solution {
2 public TreeNode inOrderSuccessor(TreeNode root, TreeNode target) {
3 if (target == null) return null;
4 if (target.right != null) return minValue(target.right);
5 TreeNode succ = null;
6 while (root != null) {
7 if (target.val < root.val) {
8 succ = root;
9 root = root.left;
10 } else if (target.val > root.val) {
11 root = root.right;
12 } else {
13 break;
14 }
15 }
16 return succ;
17 }
18
19 private TreeNode minValue(TreeNode root) {
20 while (root.left != null) {
21 root = root.left;
22 }
23 return root;
24 }
25 }