完全二叉树
思想:
层次遍历
(1)有右无左,False
(2)左右不全,必须接下来的每一个节点都是叶节点,才是True
import queue
def isCBTtree(head):
if not head:
return False
que=queue.Queue()
que.put(head)
flag=False #激活判断
while que:
head=que.get()
if (not head.left and head.right) or (flag and (head.left or head.right)):
return False
if head.left:
que.put(head.left)
if head.right:
que.put(head.right)
if not head.left or not head.right: #左右不全,阶段开启
flag=True
return True
搜索二叉树:
中序遍历的结果是升序
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.res=[]
def isValidBST(self, root):
inorder = self.inorder(root)
return inorder == sorted(set(inorder))
def inorder(self, root):
if not root:
return []
self.inorder(root.left)
self.res.append(root.val)
self.inorder(root.right)
return self.res