标签:
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) { 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 }
Inorder Successor in Binary Search Tree
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5745222.html