700. Search in a Binary Search Tree

Posted Keep Learning

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了700. Search in a Binary Search Tree相关的知识,希望对你有一定的参考价值。

/**
 * 700. Search in a Binary Search Tree
 * https://leetcode.com/problems/search-in-a-binary-search-tree/description/
 * */

class TreeNode(var `val`: Int) {
    var left: TreeNode? = null
    var right: TreeNode? = null
}

class Solution {
    fun searchBST(root_: TreeNode?, targe: Int): TreeNode? {
        if (root_ == null) {
            return null
        }
        var root = root_
        val stack = Stack<TreeNode>()
        //use inorder: root,left,right
        while (stack.isNotEmpty() || root != null) {
            if (root != null) {
                stack.add(root)
                root = root.left
            } else {
                root = stack.pop()
                if (root.`val`==targe){
                    return root
                }
                root = root.right
            }
        }
        return null
    }
}

 

以上是关于700. Search in a Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章

700. Search in a Binary Search Tree

LeetCode 700 Search in a Binary Search Tree 解题报告

[LeetCode&Python] Problem 700. Search in a Binary Search Tree

LeetCode 700.二叉树中的搜索

Search in a Binary Search Tree

Find mode in Binary Search Tree