zoukankan      html  css  js  c++  java
  • 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)
            
    if x is None 只有None成立
    if not x None,  False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()都相当于False
    取上面的情况,就成立
    if not x is None 相当于if not (x is None),推荐这种写法:if x is not None
  • 相关阅读:
    array_count_values源码
    php 编译安装记录
    mysql 安装的过程做个记录
    初识highcharts 库
    php 不重新编译增加新扩展的方法
    备考PMP
    Beyond Compare4破解--写reg脚本删除注册表
    SourceTree 跳过登录
    正则 (?=exp)
    springmvc--处理器的返回参数
  • 原文地址:https://www.cnblogs.com/captain-dl/p/10128945.html
Copyright © 2011-2022 走看看