二叉树相关算法问题python实现

二叉树算法问题


二叉树深度

树的深度 = max(左子树深度,右子树深度)+1,直接递归很简单

def depth(root):
	if not root:
		return 0
	return max(depth(root.left),depth(root.right))+1

平衡二叉树

法一:通过计算每个子树的深度

def isSym(root)if not root:
		return True
	left = depth(root.left)
	right = depth(root.right)
	return abs(left - right) <2 and isSym(root.left) and isSym(root.right)

法二:基于后序遍历依次往上去判断

def isSym2(root):
		def check(root):
			if not root:
				return 0
	# 判断左子树,这个返回值时根据下面abs(left - right) < 2这个判断,然后从下依次往上
			left = check(root.left)
			if left == -1:
				return -1
			right = check(root.right) # 判断右子树,同理
			if right == -1:
				return -1
			if abs(left - right) < 2:
				return max(left,right)+1
			return -1 
	return check(root) != -1

对称二叉树

    def isSymmetric(self, root):
        if not root:
            return True
        def check(l,r):
            if not l and not r:
                return True
            if (not l or not r) or l.val != r.val:
                return False
            return check(l.left,r.right) and check(l.right,r.left)
        return check(root.left,root.right)

二叉树遍历问题

二叉树层次打印

在这里插入图片描述

如上图二叉树打印成格式 [[4],[2,5],[1,3,6]]
(一) 借助level把一层放在一起

def level_print(root):
	if not root:
		return []
	st = [[root,0]]
	result = [[]]
	level = 0
	while st:
		temp = st.pop()
		node = temp[0]
		level = temp[1]
		if len(result) == level:
			result.append([])
			# 同一层一个level
		result[level].append(node.val)
		# 使用栈时,先进后出,先放进去右节点
		if node.right:
			st.append([node.right,level+1])
		if node.left:
			st.append([node.left,level+1])
	return result

(二) 使用临时列表 需要这个地方存放节点需要一个队列完成,因为每次循环都要弹出来的一个节点并把此节点的左右节点放进去,这样不能保证每一行的节点依次打印

def list_print(root):
	if not root:
		return []
	st = [root]
	result = []
	while st:
		temp = []
		# 提前记录栈里个数
		l = len(st)
		# 循环栈里个数的次数
		for i in range(l):
			node = st.pop(0)
			# 依次将一层的值放进去
			temp.append(node.val)
			# 引出下一层,先进后出
			if node.left:
				st.append(node.left)
			if node.right:
				st.append(node.right)
		result.append(temp)
	return result

之字形打印

上图二叉树打印成 [[4],[5,2],[1,3,6]]
(一) 根据每层打印左右顺序不同,确定放入栈的顺序

def z_print(root):
	if not root:
		return []
	st1 = [root]
	st2 = []
	result = []
	while st1 or st2:
		if st1:
			temp1 = []
			while st1:
				node = st1.pop()
				temp1.append(node.val)
				if node.left:
					st2.append(node.left)
				if node.right:
					s2.append(node.right)
			result.append(temp1)
		if st2:
			temp2 = []
			while st2:
				node = st2.pop()
				while st2:
					temp2.append(node.val)
					if node.right:
						st1.append(node.right)
					if node.left:
						st1.append(node.left)
				result.append(temp2)
	return result

(二) 设置标注

def z_print(root):
	if not root:
		return []
	st = [root]
	result = []
	flag = -1
	while st:
		temp = []
		l = len(st)
		for i in range(l):
			node = st.pop(0)
			temp.append(node.val)
			if node.right:
				st.append(node.right)
			if node.left:
				st.append(node.left)
		if flag == -1:
			temp = temp[::-1]
		result.append(temp)
		flag *= -1
	return result
		

重建二叉树

根据前序序列preorder和中序序列inorder ,构建二叉树,思路:根据前序序列提供根节点值,确定根节点在中序序列中对应的索引值,分成左子树和右子树,进行递归完成。
class TreeNode:
	def __init__(self,val):
		self.val = val
		self.left = None
		self.right = None
def buildtree(preorder,inorder):
	in_count = {}
	for i in range(len(inorder)):
		in_count[inorder[i]] = i
	def build(rootIndex, left,right):
		if left > right:
			return None
		root = TreeNode(preorder[rootIndex])
		index = in_count[preorder[rootIndex]]
		root.left = build(rootIndex+1,left,index-1)
		root.right = build(rootIndex + index+1 - left, index+1, right)
		return root 
	return build(0,0,len(preorder)-1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值