zoukankan      html  css  js  c++  java
  • 285. Inorder Successor in BST

    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
        }
    }
  • 相关阅读:
    UltraSoft
    UltraSoft
    UltraSoft
    UltraSoft
    UltraSoft
    [技术博客] 使用邮箱验证并激活账户
    OO第一单元作业总结
    OO第一单元总结
    buaaoo_second_assignment
    buaaoo_first_improvement
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/11117847.html
Copyright © 2011-2022 走看看