首页 > 其他 > 详细

285. Inorder Successor in BST

时间:2019-07-02 09:17:19      阅读:94      评论:0      收藏:0      [点我收藏+]
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
    }
}

 

285. Inorder Successor in BST

原文:https://www.cnblogs.com/johnnyzhao/p/11117847.html

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