Find Successor & Predecessor in BST

First, we use recursive way.

Successor

 public class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
if (root == null) {
return null;
}
if (root.val <= p.val) {
return inorderSuccessor(root.right, p);
} else {
TreeNode left = inorderSuccessor(root.left, p);
return left == null ? root : left;
}
}
}

Predecessor

 public class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
if (root == null) {
return null;
}
if (root.val >= p.val) {
return inorderSuccessor(root.left, p);
} else {
TreeNode right = inorderSuccessor(root.right, p);
return right == null ? root : right;
}
}
}
上一篇:java读写excel文件( POI解析Excel)


下一篇:Jxl创建Excel文件和解析Excel文件