二叉树

1,二叉树的定义
二叉树的结构:二叉树由根节点和左右子树组成,二叉树的左子树和右子树分别为二叉树。这种结构使得有关二叉树的问题大部分可以用递归的算法解决。
2,二叉树的序列化,使得内存中的二叉树可以在文件中存储起来。
二叉树的遍历有:前序,中序,后序遍历,层序遍历。
前序遍历(根节点->左子树->右子树)
中序遍历(左子树->根节点->右子树)
后序遍历(左子树->右子树->根节点)
层序遍历二叉树,即从上到下,同层节点从左到右遍历每个节点。通常会借助“队列”这种数据结构,保证“先进先出”。
Python中的队列结构在标准库中,from collections import deque
3,二叉树的反序列化(重建二叉树)

"""从前序遍历序列和中序遍历序列构建二叉树(无重复元素)
Given preorder and inorder traversal of a tree, 
construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
preorder第一个元素为root,
在inorder里面找到root,在它之前的为左子树(长l1),之后为右子树(长l2)。
preorder[1]到preorder[l1]为左子树,之后为右子树,分别递归。"""
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
        if not preorder:
            return None
        root = TreeNode(preorder[0])
        loc = inorder.index(preorder[0])
        root.left = self.buildTree(preorder[1 : loc + 1], inorder[ : loc])
        root.right = self.buildTree(preorder[loc+1 : ], inorder[loc+1: ])
        return root


"从中序和后序序列构建二叉树"
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
        if not postorder:
            return None
        root=TreeNode(postorder[-1])
        loc = inorder.index(postorder[-1])
        #inorder[:loc]#左子树,长度为loc;postorder[:loc]
        #inorder[loc+1:]#右子树postorder[loc:-1]
        root.left = self.buildTree( inorder[:loc], postorder[:loc])
        root.right = self.buildTree(inorder[loc+1:], postorder[loc:-1] )
        return root

3,二叉树的镜像(可以用递归来做)
二叉树的镜像定义:源二叉树
8
/
6 10
/ \ /
5 7 9 11
镜像二叉树
8
/
10 6
/ \ /
11 9 7 5
4,判断一颗二叉树是否是对称的,注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。(可以用递归来做)
5,判断给定的二叉树是否是二叉搜索树
6.二叉树的最大深度leetcode T104

"""二叉树的最大深度(二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。) 
leetcode  T104 
The maximum depth is the number of nodes 
along the longest path from the root node down to the farthest leaf node.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。"""
class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if not root:
            return 0
        return max(self.maxDepth(root.left),self.maxDepth(root.right))+1

7.路径总和

"""路径总和
Given a binary tree and a sum, 
determine if the tree has a root-to-leaf path 
such that adding up all the values along the path equals the given sum.

Note: A leaf is a node with no children.

来源:力扣(LeetCode)
链接: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
        if root.left == None and root.right == None:
            return sum-root.val == 0
        return self.hasPathSum(root.left,sum-root.val) or self.hasPathSum(root.right,sum-root.val)

8.路径总和II

"""路径总和II 
Given a binary tree and a sum, 
find all root-to-leaf paths where each path's sum equals the given sum.

Note: A leaf is a node with no children.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处T113"""
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
        res=[]#记录所有路径数字
        path=[]#记录每一条路径上的数字

        def help(root,sum,path):

            if not root:
                return []

            if not root.left and not root.right and root.val == sum:
                path.append(root.val)
                res.append(path)
            if root.left:
                help(root.left,sum-root.val,path+[root.val])
            if root.right:
                help(root.right,sum-root.val,path+[root.val])

        help(root,sum,path)
        return res
另一种写法,等同于上面
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

def help(root,s,v,target):
    if not root:
        return 
    if root.left is None and root.right is None and root.val == target:

            s.append(root.val)
            v.append(s)
    
    if root.left:
        help(root.left,s+[root.val],v,target-root.val)
    if root.right:
        help(root.right,s+[root.val],v,target-root.val)

class Solution(object):
    def pathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: List[List[int]]
        """
        s=[] #记录每一条路径上的数字
        v=[] #记录所有路径数字
        help(root,s,v,sum)
        return v

9.二叉树的最小深度

"""
Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes
along the shortest path from the root node down to the nearest leaf node.

Note: A leaf is a node with no children.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-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 minDepth(self, root: TreeNode) -> int:
        if not root:
            return 0
        left=self.minDepth(root.left)
        right=self.minDepth(root.right)
        if left and right:
            return min(left,right)+1
        else:#此时right,left至少有一个树为空
            return left+right+1

2020年7月23日22:44:38

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容