import java.util.* /** * Lock by Leetcode * 285. Inorder Successor in BST * https://www.lintcode.com/problem/inorder-successor-in-bst/description * * Given a binary search tree (See Definition) and a node in it, * find the in-order successor of that node in the BST. If the given node has no in-order successor in the tree, return null. Challenge O(h), where h is the height of the BST. */ class TreeNode(var `val`: Int) { var left: TreeNode? = null var right: TreeNode? = null } //inorder: root->left->right class Solution { fun inorderSuccessor(root_: TreeNode?, node: TreeNode): TreeNode? { var findIt = false var root = root_ val stack = Stack<TreeNode>() stack.push(root) while (root != null || stack.size > 0) { if (root != null) { stack.push(root) root = root.left!! } else { root = stack.pop() if (findIt) { return root } if (root.`val` == node.`val`) { findIt = true//if found the node, the next node is the result } root = root.right } } return null } }
原文:https://www.cnblogs.com/johnnyzhao/p/11117847.html