LintCode 11. 二叉查找树中搜索区间 Python

描述

给定两个值 k1 和 k2(k1 < k2)和一个二叉查找树的根节点。找到树中所有值在 k1 到 k2 范围内的节点。即打印所有x (k1 <= x <= k2) 其中 x 是二叉查找树的中的节点值。返回所有升序的节点值。

样例

如果有 k1 = 10 和 k2 = 22, 你的程序应该返回 [12, 20, 22].

    20
   /  \
  8   22
 / \
4   12

分析

二叉树的值采用中序遍历

代码

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: param root: The root of the binary search tree
    @param k1: An integer
    @param k2: An integer
    @return: return: Return all keys that k1<=key<=k2 in ascending order
    """
    def __init__(self):
        self.x = []
    def searchRange(self, root, k1, k2):
        # write your code here
        if root is None :
            return self.x 
        if root.left:
            self.searchRange(root.left, k1, k2)
        if root.val is not None and k1 <= root.val <= k2:
            print(root.val)
            self.x.append(root.val)
        if root.right:
            self.searchRange(root.right, k1, k2)
        
        return self.x 
            

猜你喜欢

转载自blog.csdn.net/weixin_44409630/article/details/85851556