求二叉搜索樹的中序后繼節點
分析:
1. 如果目標節點的右子樹不為空,則返回右子樹的最小節點;
2. 如果目標節點的右子樹為空,則從根節點開始遍歷。
實現代碼如下:
分析:
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 }
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 }