二叉树的前、中、后序遍历,层次遍历,二叉树的深度

1. 前序遍历(根、左、右);中序遍历(左、根、右);后序遍历(左、右、根) 

# 前序遍历
def pre_order(root):
    if root:
        print(root.data)
        pre_order(root.lchild)
        pre_order(root.rchild)

# 中序遍历
import sys
sys.setrecursionlimit(100000)  # python默认递归深度有限,解决方式是手工设置递归调用深度
def in_order(root):
    if root:
        in_order(root.lchild)
        print(root.data)
        in_order(root.rchild)

# 后序遍历
def post_order(root):
    if root:
        in_order(root.lchild)
        in_order(root.rchild)
        print(root.data)

2. 层次遍历(用队列实现)

def level_order(root):
    list=[]
    list.append(root)
    while len(list)>0:
        node=list.pop(0)
        print(node.data)
        if node.lchild:
            list.append(node.lchild)
        if node.rchild:
            list.append(node.rchild)
            

2.1 二叉树的层序遍历LeetCode例题:用二维数组保存节点值,每一层的节点保存在一个一维数组中。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
        if not root:            # 先判断节点是否为空
            return []
        node_list=[]            # 存节点(二维数组),模拟队列
        level_list=[]           # 存节点值(二维数组)
        node_list.append([root])
        level_list.insert(0,[root.val])     # 因为是倒序,所以要插入到表头
        while node_list:        # 如果队列不空,保证每一层的节点都遍历一遍
            node=node_list.pop(0)
            level=[]            # 存每一层的节点   
            level_val=[]        # 存每一层的节点值
            for elem in node:
                if elem.left:
                    level.append(elem.left)
                    level_val.append(elem.left.val)
                if elem.right:
                    level.append(elem.right)
                    level_val.append(elem.right.val)
            if level:           # 如果下一层有节点,一定要有这个判断条件,否则程序一直append([]),会进入死循环
                node_list.append(level)
                level_list.insert(0,level_val)   
        return level_list

​​​3. 二叉树的深度

class Solution:
    def maxDepth(self , root: TreeNode) -> int:
        # write code here
        if not root:                            # 根节点为空
            return 0
        elif not root.left and not root.right:  # 左右子树全为空
            return 1
        else:
            return max(1+self.maxDepth(root.left),1+self.maxDepth(root.right))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值