二叉树 leetcode心得

class Node(object):
    def __init__(self,root):
        self.value=root
        self.left=None
        self.right=None

class Solution(object):   #判断二叉树深度  n-1/1递归法+递归赋值
    def howhigh(self,root):
        return max(self.howhigh(root.left),self.howhigh(root.right))+1

    def BST(self,root):    #验证二叉树,利用中序思想
        result=[]
        self.zhongxv(root,result)
        for i in range(len(result)-1):
            if result[i]>result[i+1]:
                return False
        return True

     def zhongxv(self,root,result):  #中序搜索,常规递归
         if not root:
             return
         self.zhongxv(root.left,result)
         result.append(root.val)
         self.zhongxv(root.right,result)
         return result

     def isSym(self,root):   #判断对称二叉树
         if not root:
             return True
         return self.judge(root.left,root.right)

     def judge(self,left,right):    #n-1/1递归法
         if not left and not right:
             return True
         if left and right and left.val==right.val:
             return judge(left.left,right.right)  and judge(left.right,right.left)
         return False

     def travel(self,root):    #二叉树层次遍历  ,利用列表删添操作
         tmp=[root]
         result=[]
         while tmp:
             p=[]
             for i in range(len(tmp)):
                 a=tmp.pop(0)
                 p.append(a)
                 if root.left:
                     tmp.append(root.left)
                 if root.right:
                     tmp.append(root.right)
             result.append(p)
         return result

     def zhuanhuan(self,nums):  #将列表转换为二叉搜索树
         n=len(nums)
         mid=n//2
         if not nums:
             return None
         root=Node(nums[mid])
         root.left=self.zhuanhuan(nums[:mid])
         root.right=self.zhuanhuan(nums[mid+1:])
         return root




猜你喜欢

转载自blog.csdn.net/weixin_38740463/article/details/87896488