二叉树练习题(一) 二叉树的遍历

本文详细介绍了二叉树的遍历方法,包括先序、中序、后序及层次遍历,同时探讨了之字形打印和满二叉树判断等高级主题,为读者提供了深入理解二叉树结构的基础。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述
练习题1:如何根据二叉树的遍历结果重置二叉树:
对于先序遍历我们知道,最先出现的一般是根节点,而中序遍历一般将根节点出现在中间,后序遍历将跟节点出现在最后,我们可以根据根节点所在为止划分子树,然后重置二叉树
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
例题1:对于上述二叉树,请实现层次遍历、先序遍历、中序遍历和后序遍历


'''
二叉树的遍历
将以下二叉树分别用先序遍历、中序遍历、后序遍历和层次遍历进行遍历
      0
   1      2
 3   4   5  6
7 8 9
先序遍历:中左右
中序遍历:左中右
后序遍历:左右中
'''
class TreeNode:
     def __init__(self, x):
         self.val = x
         self.left=None
         self.right=None
#生成二叉树
node_0=TreeNode(0)
node_1=TreeNode(1)
node_2=TreeNode(2)
node_3=TreeNode(3)
node_4=TreeNode(4)
node_5=TreeNode(5)
node_6=TreeNode(6)
node_7=TreeNode(7)
node_8=TreeNode(8)
node_9=TreeNode(9)

node_0.left=node_1
node_0.right=node_2
node_1.left=node_3
node_1.right=node_4
node_2.left=node_5
node_2.right=node_6
node_3.left=node_7
node_3.right=node_8
node_4.left=node_9
#前序遍历
def priosearch(head):
    if head==None:
        return
    print(head.val,end=' ')
    priosearch(head.left)
    priosearch(head.right)
priosearch(node_0)
#0 1 3 7 8 4 9 2 5 6 
#中序遍历
def midsearch(head):
    if head==None:
        return
    midsearch(head.left)
    print(head.val,end=' ')
    midsearch(head.right)
midsearch(node_0)
#7 3 8 1 9 4 0 5 2 6 
#后序遍历
def backsearch(head):
    if head==None:
        return
    backsearch(head.left)
    backsearch(head.right)
    print(head.val,end=' ')
backsearch(node_0)
#层次遍历,利用队列的方式去遍历
def cengcisearch(head):
    arr=[]
    arr.append(head)
    while arr:
        c_root=arr.pop(0)
        print(c_root.val,end=' ')
        if c_root.left is not None:
            arr.append(c_root.left)
        if c_root.right is not None:
            arr.append(c_root.right)
cengcisearch(node_0)            
#0 1 2 3 4 5 6 7 8 9 

习题2:剑指offer32
按层打印二叉树,从上到下从左向右
在这里插入图片描述

'''
从上至下层次打印二叉树
如:
        8
   6         10
5    7    9      11
'''
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
Node1=TreeNode(8)
Node2=TreeNode(6)
Node3=TreeNode(10)
Node4=TreeNode(5)
Node5=TreeNode(7)
Node6=TreeNode(9)
Node7=TreeNode(11)
Node1.left=Node2
Node1.right=Node3
Node2.left=Node4
Node2.right=Node5
Node3.left=Node6
Node3.right=Node7

head=Node1
def cenciprint(head):
    if head is None:
        return
    list1=[] #当前节点要打印的元素
    list2=[] #将节点弹出的下一层节点暂时存储的数组
    list1.append(head)
    while list1 or list2:
        while list1:
            c_root=list1.pop(0)
            list2.append(c_root)
        #此时list2已经将这一层节点全部存储了
        while list2:
        #将这一层的节点全部打印,并将当前节点的左右节点放入list1中
            root=list2.pop(0)
            print(root.val,end=' ')
            if root.left is not None:
                list1.append(root.left)
            if root.right is not None:
                list1.append(root.right)
        print('\n')
cenciprint(Node1)

解析:使用两个list来实现,首先放入根节点,将根节点的所有子节点遍历并放入list2,从最开始的元素从list2依次弹出,每次打印这个元素,并将其加入list1,相当于在list1进行出栈并添加子树时,先将子树存储起来以防止不断出栈,这样list2中每次存储的都是每一层的所有元素,当两个list1、list2都为空时代表已经全部遍历结束。
习题3:之字形打印二叉树
在这里插入图片描述

'''
之字形打印二叉树
               1
        2                3
    4      5         6       7
  8   9  10  11    12  13  14  15
打印出来的结果:
1
3 2
4 5 6 7
15 14 13 12 11 10 9 8   
'''
##测试:来回打印
Node1=TreeNode(1)
Node2=TreeNode(2)
Node3=TreeNode(3)
Node4=TreeNode(4)
Node5=TreeNode(5)
Node6=TreeNode(6)
Node7=TreeNode(7)
Node8=TreeNode(8)
Node9=TreeNode(9)
Node10=TreeNode(10)
Node11=TreeNode(11)
Node12=TreeNode(12)
Node13=TreeNode(13)
Node14=TreeNode(14)
Node15=TreeNode(15)
Node16=TreeNode(16)
Node1.left=Node2
Node1.right=Node3
Node2.left=Node4
Node2.right=Node5
Node3.left=Node6
Node3.right=Node7
Node4.left=Node8
Node4.right=Node9
Node5.left=Node10
Node5.right=Node11
Node6.left=Node12
Node6.right=Node13
Node7.left=Node14
Node7.right=Node15
def zhizi_print(head,right_left_triger=False):
    if head is None:
        return
    list1=[] #临时存储下一层节点的值,以队列的形式存储,后面进,前面出
    list2=[] #存储当前节点要打印的值
    list1.append(head)
    while list1 or list2:
        while list1:
            c_root=list1.pop(0)
            list2.append(c_root)         
        while list2:
            if right_left_triger==True:#从右向左打印
                root=list2.pop()
                print(root.val,end=' ')
                if root.right is not None:
                    list1.append(root.right)
                if root.left is not None:
                    list1.append(root.left)
                #此时list1中存储的元素也是从右往左的所以需要将list1颠倒
                #list1=list1[::-1]
            else: #从左向右打印
                root=list2.pop(0)
                print(root.val,end=' ')
                if root.left is not None:
                    list1.append(root.left)
                if root.right is not None:
                    list1.append(root.right)
        #arr=[i.val for i in list1]
        #print(arr)
        if right_left_triger==True:
            right_left_triger=False
            list1=list1[::-1]
        else:
            right_left_triger=True   
        print('\n')
zhizi_print(Node1)                 

在这里插入图片描述
在上一道每行打印二叉树的基础上进行修改,从左到右和从右到左只需改变list2的弹出顺序,即一个弹出最前面的元素,一个弹出最右边的元素,每次循环完成后改变left的值,如果left时True改为False,如果是False改为True.
习题4:判断二叉树是否为满二叉树
首先完全二叉树树的定义是,加入一个二叉树有h层,除了h层外,其余h-1层均满二叉树状态,第h层所有的节点均从最左边开始生长。

(1)非递归定义 树(tree)是由n(n≥0)个结点组成的有限集合。n=0的树称为空树;n>0的树T: ① 有且仅有个结点n0,它没有前驱结点,只有后继结点。n0称作树的根(root)结点。 ② 除结点外n0 , 其余的每个结点都有且仅有个直接前驱结点;有零个或多个直接后继结点。 (2)递归定义 颗大树分成几个大的分枝,每个大分枝再分成几个小分枝,小分枝再分成更小的分枝,… ,每个分枝也都是颗树,由此我们可以给出树的递归定义。 树(tree)是由n(n≥0)个结点组成的有限集合。n=0的树称为空树;n>0的树T: ① 有且仅有个结点n0,它没有前驱结点,只有后继结点。n0称作树的根(root)结点。 ② 除根结点之外的其他结点分为m(m≥0)个互不相交的集合T0,T1,…,Tm-1,其中每个集合Ti(0≤i<m)本身又是棵树,称为根的子树(subtree)。 2、掌握树的各种术语: (1) 父母、孩子与兄弟结点 (2) 度 (3) 结点层次、树的高度 (4) 边、路径 (5) 无序树、有序树 (6) 森林 3、二叉树的定义 二叉树(binary tree)是由n(n≥0)个结点组成的有限集合,此集合或者为空,或者由个根结点加上两棵分别称为左、右子树的,互不相交的二叉树组成。 二叉树可以为空集,因此根可以有空的左子树或者右子树,亦或者左、右子树皆为空。 4、掌握二叉树的五个性质 5、二叉树的二叉链表存储。
### 关于二叉树遍历练习题 以下是几道典型的二叉树遍历题目,涉及已知两种遍历结果求第三种遍历结果: #### 题目 **描述**: 已知某棵二叉树的先序遍历为 `ABDEGHCFIJ`,中序遍历为 `DBGEHACIFJ`,试求其后序遍历。 **解答思路**: 1. 根据先序遍历的第个节点确定根节点为 A[^2]。 2. 在中序遍历中定位到 A 的位置,左侧部分为左子树 (即 DBGEH),右侧部分为右子树 (即 CIFJ)[^3]。 3. 对左子树和右子树分别重复上述过程,逐步构建完整的二叉树结构。 4. 最终得到后序遍历结果为:`DHEGBFJICA`。 --- #### 题目二 **描述**: 某二叉树的中序遍历为 `DEFBCGA`,后序遍历为 `DFEBGCA`,试求其先序遍历。 **解答思路**: 1. 后序遍历最后个节点必然是整棵树的根节点 C[^3]。 2. 定位 C 在中序遍历中的位置,分割出左子树 DEF 和右子树 BGA。 3. 进步分析左右子树内部关系,最终得出先序遍历结果为:`CDBGFEA`。 --- #### 题目三 **描述**: 若二叉树的先序遍历为 `KLMNOPQR`,后序遍历为 `LPMRQONK`,试求其中序遍历。 **解答思路**: 1. 先序遍历个节点 K 是整个二叉树的根节点[^1]。 2. 后序遍历最后个是根节点 K,在此之前的部分属于左右子树范围 LPMRQO。 3. 利用递归方法分解各层子树,最终获得中序遍历结果为:`LPORMQN`。 --- #### 题目四 **描述**: 有二叉树,它的中序遍历为 `ABCDEFG`,后序遍历为 `BDCAFEG`,请求出这棵二叉树的先序遍历。 **解答思路**: 1. 后序遍历的最后个字符 G 表明它是整棵树的根节点[^3]。 2. 查找 G 在中序遍历的位置,将其分为两部分 ABCDEF(左子树)和空集(无右子树)。 3. 类似方式继续拆分直到完成全部层次划分,最终得到先序遍历结果为:`GFEDCBA`。 --- ```python # Python 实现辅助函数用于验证答案 class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def build_tree(preorder, inorder): if not preorder or not inorder: return None root_val = preorder[0] root_index_inorder = inorder.index(root_val) root = TreeNode(root_val) root.left = build_tree(preorder[1:root_index_inorder+1], inorder[:root_index_inorder]) root.right = build_tree(preorder[root_index_inorder+1:], inorder[root_index_inorder+1:]) return root def post_order_traversal(root): result = [] stack = [(root, False)] while stack: node, visited = stack.pop() if node is None: continue if visited: result.append(node.val) else: stack.append((node, True)) stack.append((node.right, False)) stack.append((node.left, False)) return result ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值