二叉树(python)

编程入门 行业动态 更新时间:2024-10-27 01:36:45

<a href=https://www.elefans.com/category/jswz/34/1769924.html style=二叉树(python)"/>

二叉树(python)

二叉树解体的思维模式分两类:
1、「遍历」的思维模式:是否可以通过遍历一遍二叉树得到答案?如果可以,用traverse函数配合外部变量实现。
2、「分解问题」的思维模式:是否可以通过子问题(子树)的答案推导出原文的答案?如果可以,写出递归函数的定义,并充分利用该函数的返回值。

二叉树的最大深度

遍历思维

class TreeNode:def __init__(self, val=0, left=None, right=None):self.val = valself.left = leftself.right = right
class Solution:def maxDepth(self, root):res = 0depth = 0res = self.traverse(root, res, depth)return resdef traverse(self, root, res, depth):if not root:return resdepth += 1if not root.left and not root.right:res = max(res, depth)res = self.traverse(root.left, res, depth)res = self.traverse(root.right, res, depth)depth -= 1return res

分解思维

class Solution:def mathDepth(self, root):if not root: return 0else:left_h = self.maxDepth(root.left)right_h = self.maxDepth(root.right)return max(left_h, right_h)+1

二叉树的直径

二叉树的 直径 是指树中任意两个节点之间最长路径的 长度。这条路径可能经过也可能不经过根节点 root 。每一条二叉树的直径长度,就是一个节点的左右子树的最大深度之和.

class Solution:def diameterOfTree(self, root):self.res = 0def maxDepth(root):if not root: return 0leftMax = maxDepth(root.left)rightMax = maxDepth(root.right)cur = leftMax + rightMaxself.res = max(cur, self.res)return 1 + max(leftMax, rightMax)maxDepth(root)return self.res

层序遍历

def levelTraverse(root):if not root: returnq = deque()q.append(root)# while 循环和 for 循环分管从上到下和从左到右的遍历while q:level = len(q)for i in range(level):cur = q.popleft()if cur.left:q.append(cur.left)if cur.right:q.append(cur.right)

更多推荐

二叉树(python)

本文发布于:2023-12-03 13:35:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1655927.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:二叉树   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!