首页 > 其他 > 详细

Find Successor & Predecessor in BST

时间:2015-11-08 14:24:01      阅读:146      评论:0      收藏:0      [点我收藏+]

First, we use recursive way.

Successor

 1 public class Solution {
 2     public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
 3         if (root == null) {
 4             return null;
 5         }
 6         if (root.val <= p.val) {
 7             return inorderSuccessor(root.right, p);
 8         } else {
 9             TreeNode left = inorderSuccessor(root.left, p);
10             return left == null ? root : left;
11         }
12     }
13 }

Predecessor

 1 public class Solution {
 2     public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
 3         if (root == null) {
 4             return null;
 5         }
 6         if (root.val >= p.val) {
 7             return inorderSuccessor(root.left, p);
 8         } else {
 9             TreeNode right = inorderSuccessor(root.right, p);
10             return right == null ? root : right;
11         }
12     }
13 }

 

Find Successor & Predecessor in BST

原文:http://www.cnblogs.com/ireneyanglan/p/4946829.html

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