700. Search in a Binary Search Tree

Posted captain-dl

tags:

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

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def searchBST(self, root, val):
        """
        :type root: TreeNode
        :type val: int
        :rtype: TreeNode
        """
        if root==None : return NULL
        
        if root.val==val: return root
        
        elif root.val<val:
            self.searchBST(root.right,val)
        else:
            self.searchBST(root.left,val)

问题:不明白树的数据结构在python中是如何实现的?

 

    def __init__(self, root_value):
        self.root = root_value
        self.leftchild = None
        self.rightchild = None

 

 

 

终于看,明白了,如图:

技术分享图片

 

 

上面的代码有问题:

class Solution(object):
    def searchBST(self, root, val):
        """
        :type root: TreeNode
        :type val: int
        :rtype: TreeNode
        """
        if not root:
            return None
        if root.val == val:
            return root
        elif root.val < val:
            return self.searchBST(root.right, val)
        else:
            return self.searchBST(root.left, val)
        

 

以上是关于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