Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
Note: If the given node has no in-order successor in the tree, return null
.
Solution:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public class Result{ TreeNode resNode; boolean foundP; boolean foundRes; public Result(){ resNode = null; foundP = false; foundRes = false; } } public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { Result res = new Result(); searchTree(root,p,res); return res.resNode; } public void searchTree(TreeNode cur, TreeNode p, Result res){ if (cur==null){ return; } searchTree(cur.left,p,res); if (res.foundP && res.foundRes) return; if (res.foundP){ res.resNode = cur; res.foundRes = true; return; } if (cur == p){ res.foundP = true; } searchTree(cur.right,p,res); } }