首页 > 其他 > 详细

Inorder Successor in Binary Search Tree

时间:2016-08-07 00:54:07      阅读:93      评论:0      收藏:0      [点我收藏+]

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!