Python实现二叉树的一些套路模板

 

 

目录

1.先序遍历递归与非递归

2.中序遍历递归与非递归

3.后序遍历的递归与非递归

4.层次遍历

5.二叉树的最大深度

6.验证二叉搜索树

7.从中序与后序遍历序列构造二叉树

8.从前序与中序遍历序列构造二叉树


1.先序遍历递归与非递归

def preorder_recursive(root):#先序遍历,递归版
    if not root:
        return None
    print(root.val)
    preorder_recursive(root.left)
    preorder_recursive(root.right)
def preorder_iteration_1(root):#先序遍历,迭代版1
    if not root:
        return None
    stack = []
    node = root
    while node or len(stack)>0:
        while node:
            print(node.val)
            stack.append(node.left)
            node = node.left
        node = stack.pop()
        node = node.right
def preorder_iteration_2(root):
    if not root:
        return None
    stack = [root]
    while len(stack)>0:
        print(root.val)
        if root.right:
            stack.append(root.right)
        if root.left:
            stack.append(root.left)
        root = stack.pop()

2.中序遍历递归与非递归

def inorder_recursive(root):#递归版本
    if not root:
        return None
    inorder_recursive(root.left)
    print(root.val)
    inorder_recursive(root.right)
def inorder_iteration(root):#非递归版本
    if not root:
        return None
    stack = []
    node = root
    while node or len(stack)>0:
        while node:
            stack.append(node)
            node = node.left
        node = stack.pop()
        print(node.val)
        node = node.right

3.后序遍历的递归与非递归

def postOrder_recursive(root):#递归版本
    if not root:
        return None
    postOrder_recursive(root.left)
    postOrder_recursive(root.right)
    print(root.val)
def postOrder_iteration(root):
    # 使用两个栈结构
    # 第一个栈进栈顺序:左节点->右节点->根节点
    # 第一个栈弹出顺序: 根节点->右节点->左节点
    # 最后第二个栈依次出栈
    if not root:
        return None
    stack1 = [root]
    stack2 = []
    while len(stack1)>0:
        node = stack1.pop()
        stack2.append(node)
        if node.left:
            stack1.append(node.left)
        if node.right:
            stack1.append(node.right)
    while len(stack2)>0:
        node = stack2.pop()
        print(node.val)

4.层次遍历

def layer_iteration(root):
    if not root:
        return None
    queue = [root]
    while len(queue)>0:
        node = queue.pop(0)
        print(node.val)
        if node.left:
            queue.append(node.left)
        if node.right:
            queue.append(node.right)

5.二叉树的最大深度

def Depth(root):
    if not root:
        return 0
    Ldepth = Depth(root.left)
    Rdepth = Depth(root.right)
    return (max(Ldepth,Rdepth)+1)

6.验证二叉搜索树

leetcode的原题

class Solution(object):
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        return self.valid(root, float('-inf'),float('inf'))  #float('-inf'),float('inf')表示正负无穷
    def valid(self, root, min, max):
        if not root:
            return True
        if root.val >= max or root.val <= min:
            return False
        return self.valid(root.left, min, root.val) and self.valid(root.right, root.val, max)

7.从中序与后序遍历序列构造二叉树

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

8.从前序与中序遍历序列构造二叉树

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

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值