码迷,mamicode.com
首页 > 其他好文 > 详细

Inorder Successor in Binary Search Tree

时间:2016-08-07 00:55:55      阅读:139      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!