datawhale第五次打卡博客class TreeNode: def __init__(self,val): self.val=val; self.left=None; self.ri

实现一个二叉查找树,并且支持插入、删除、查找操作

实现查找二叉查找树中某个节点的后继、前驱节点

实现二叉树前、中、后序以及按层遍历

class TreeNode:
	def __init__(self,val):
		self.val=val;
		self.left=None;
		self.right=None;
def insert(root,val):#插入
	if root is None:
		root=TreeNode(val);
	else:
		if valroot.val:
			root.right=insert(root.right,val);  
	return root;

def query(root,val):#查询
	if root is None:
		return ;
	if root.val is val:
		return 1;
	if root.val root.val:
		return delnum(root.right,val);
	else:                                             # 删除要区分左右孩子是否为空的情况
		if(root.left and root.right):
			
			tmp=finmin(root.right);             #找到后继结点
			root.val=tmp.val;
			root.right=delnum(root.right,val);    #实际删除的是这个后继结点
			
		else:
			if root.left is None:
				root=root.right;
			elif root.right is None:
				root=root.left;
	return root;

 

 

 

并完成leetcode上的验证二叉搜索树(98)及二叉树 层次遍历(102,107)!(选做)(保留往期第四天任务)注:这个跟下面的习题有重复

  • 练习:

Invert Binary Tree(翻转二叉树)

英文版:https://leetcode.com/problems/invert-binary-tree/

中文版:https://leetcode-cn.com/problems/invert-binary-tree/

class Solution:#左右交换,递归完事
    def invertTree(self, root: TreeNode) -> TreeNode:
        if root==None:
            return None
        root.left,root.right=root.right,root.left
        self.invertTree(root.left)
        self.invertTree(root.right)
        return root

Maximum Depth of Binary Tree(二叉树的最大深度)

英文版:https://leetcode.com/problems/maximum-depth-of-binary-tree/

中文版:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if root==None:
            return 0
        left_height=self.maxDepth(root.left)
        right_height=self.maxDepth(root.right)
        height=max(left_height,right_height)+1
        return heght

Validate Binary Search Tree(验证二叉查找树)[作为可选]

英文版:https://leetcode.com/problems/validate-binary-search-tree/

中文版:https://leetcode-cn.com/problems/validate-binary-search-tree/

  • 【堆】

实现一个小顶堆、大顶堆、优先级队列

实现堆排序

利用优先级队列合并 K 个有序数组

求一组动态数据集合的最大 Top K

(选做)第三天堆排序学习(复习)

  • 练习:

Path Sum(路径总和)

英文版:https://leetcode.com/problems/path-sum/

中文版:https://leetcode-cn.com/problems/path-sum/

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def hasPathSum(self, root: TreeNode, sum: int) -> bool:
        if not root:
            return False
        sum-=root.val
        if not root.left and not root.right:
            return sum==0
        return self.hasPathSum(root.left,sum) or self.hasPathSum(root.right,sum)

你可能感兴趣的:(datawhale第五次打卡博客class TreeNode: def __init__(self,val): self.val=val; self.left=None; self.ri)