赞
踩
题目链接:https://www.nowcoder.com/practice/76fb9757332c467d933418f4adf5c73d
题中给出的序列是【从根节点开始,从上到下、同层从左到右的节点序列】
1. 根据给出的序列,构造树;
2. 根据树,得到中序遍历序列;
3. 根据【二叉搜索树中序递增】的性质,判断该树是否为二叉搜索树。
读入的数据是字符串,在【步骤2】中序遍历的时候需要把节点类型转换成【int】
- class tree:
- def __init__(self,x):
- self.val = x
- self.left = None
- self.right = None
-
- def build_tree(array,i):
- if i >= len(array) or array[i] == 'None':
- return None
- root = tree(array[i])
- root.left = build_tree(array,2*i+1)
- root.right = build_tree(array,2*i+2)
- return root
-
- def tin(res,root):
- if not root:
- return
- tin(res,root.left)
- res.append(int(root.val))
- tin(res,root.right)
- return res
-
- def compare(array):
- if not array:
- return None
- if len(array) == 1:
- return True
- pre = array[0]
- for i in range(1,len(array)):
- if array[i] <= pre:
- return False
- else:
- pre = array[i]
- return True
-
- array = input().split(',')
- if not array:
- print(False)
- elif len(array) == 1:
- print(True)
- else:
- root = build_tree(array,0)
- res = []
- tin_tree = tin(res,root)
- print(compare(tin_tree))

https://www.nowcoder.com/practice/e12c53c925754a07b5f5a2a4dd8fa829
区别仅在于:给的数据格式不同,所以构造树的过程有些不一样。
Python版本的case:73.33%,AC不了,不知道为啥?
- class Tree:
- def __init__(self,x):
- self.val = x
- self.left = None
- self.right = None
-
- def build_tree(num,rloc):
- if rloc < 0:
- return None
- a,b,c = num[rloc]
- root = Tree(a)
- root.left = build_tree(num,b-1)
- root.right = build_tree(num,c-1)
- return root
-
- def tin(res,root):
- if not root:
- return
- tin(res,root.left)
- res.append(root.val)
- tin(res,root.right)
- return res
-
- def compare(array):
- if not array:
- return True
- if len(array) == 1:
- return True
- pre = array[0]
- for i in range(1,len(array)):
- if array[i] <= pre:
- return False
- else:
- pre = array[i]
- return True
-
- lst = list(map(int,input().split()))
- n = lst[0]
- root = lst[1]-1
- num = []
- for i in range(n):
- lst = list(map(int,input().split()))
- num.append(lst)
-
- if not num:
- print('false')
- elif len(num) == 1:
- print('true')
- else:
- node = build_tree(num,root)
- res = []
- tin_tree = tin(res,node)
- if compare(tin_tree):
- print('true')
- else:
- print('false')

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。