当前位置:   article > 正文

【python】给定一棵满二叉树,判定该树是否为二叉搜索树_pycharm给定一个二叉树,判断该树是否为二叉搜索树

pycharm给定一个二叉树,判断该树是否为二叉搜索树

题目链接:https://www.nowcoder.com/practice/76fb9757332c467d933418f4adf5c73d

题中给出的序列是【从根节点开始,从上到下、同层从左到右的节点序列】

思路:

1. 根据给出的序列,构造树;

2. 根据树,得到中序遍历序列;

3. 根据【二叉搜索树中序递增】的性质,判断该树是否为二叉搜索树。

注意:

读入的数据是字符串,在【步骤2】中序遍历的时候需要把节点类型转换成【int】

  1. class tree:
  2. def __init__(self,x):
  3. self.val = x
  4. self.left = None
  5. self.right = None
  6. def build_tree(array,i):
  7. if i >= len(array) or array[i] == 'None':
  8. return None
  9. root = tree(array[i])
  10. root.left = build_tree(array,2*i+1)
  11. root.right = build_tree(array,2*i+2)
  12. return root
  13. def tin(res,root):
  14. if not root:
  15. return
  16. tin(res,root.left)
  17. res.append(int(root.val))
  18. tin(res,root.right)
  19. return res
  20. def compare(array):
  21. if not array:
  22. return None
  23. if len(array) == 1:
  24. return True
  25. pre = array[0]
  26. for i in range(1,len(array)):
  27. if array[i] <= pre:
  28. return False
  29. else:
  30. pre = array[i]
  31. return True
  32. array = input().split(',')
  33. if not array:
  34. print(False)
  35. elif len(array) == 1:
  36. print(True)
  37. else:
  38. root = build_tree(array,0)
  39. res = []
  40. tin_tree = tin(res,root)
  41. print(compare(tin_tree))

########################## 类似的题目 ###################################

https://www.nowcoder.com/practice/e12c53c925754a07b5f5a2a4dd8fa829

区别仅在于:给的数据格式不同,所以构造树的过程有些不一样。

Python版本的case:73.33%,AC不了,不知道为啥?

  1. class Tree:
  2. def __init__(self,x):
  3. self.val = x
  4. self.left = None
  5. self.right = None
  6. def build_tree(num,rloc):
  7. if rloc < 0:
  8. return None
  9. a,b,c = num[rloc]
  10. root = Tree(a)
  11. root.left = build_tree(num,b-1)
  12. root.right = build_tree(num,c-1)
  13. return root
  14. def tin(res,root):
  15. if not root:
  16. return
  17. tin(res,root.left)
  18. res.append(root.val)
  19. tin(res,root.right)
  20. return res
  21. def compare(array):
  22. if not array:
  23. return True
  24. if len(array) == 1:
  25. return True
  26. pre = array[0]
  27. for i in range(1,len(array)):
  28. if array[i] <= pre:
  29. return False
  30. else:
  31. pre = array[i]
  32. return True
  33. lst = list(map(int,input().split()))
  34. n = lst[0]
  35. root = lst[1]-1
  36. num = []
  37. for i in range(n):
  38. lst = list(map(int,input().split()))
  39. num.append(lst)
  40. if not num:
  41. print('false')
  42. elif len(num) == 1:
  43. print('true')
  44. else:
  45. node = build_tree(num,root)
  46. res = []
  47. tin_tree = tin(res,node)
  48. if compare(tin_tree):
  49. print('true')
  50. else:
  51. print('false')

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/223013
推荐阅读
相关标签
  

闽ICP备14008679号