中序和后序遍历确定二叉树​​​​​​​ + 前序和中序遍历确定二叉树

LeetCode: 

106 中序和后序遍历确定二叉树


105 前序和中序遍历确定二叉树

根据一棵树的中序遍历与后序遍历构造二叉树

注意:
你可以假设树中没有重复的元素。

例如,给出

中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7
二叉树遍历
二叉树的前序、中序、后序遍历(深度优先遍历)
遍历即将树的所有结点都访问且仅访问一次。按照根结点访问次序的不同,可以分为前序遍历,中序遍历,后序遍历。
前序遍历:根结点 -> 左子树 -> 右子树
中序遍历:左子树 -> 根结点 -> 右子树
后序遍历:左子树 -> 右子树 -> 根结点

思路:递归思想root --> root.left + root.right

中序+后序确定二叉树:后序遍历的最后一个节点为root, 中序遍历中的root将二叉树划分为左、右子树,对于左右子树同样处理:递归

前序+中序确定二叉树:前序遍历的第一个节点为root, 中序遍历中的root将二叉树划分为左、右子树,对于左右子树同样处理:递归

定义二叉树:

# Definition for a binary tree node.
from typing import List
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 len(postorder)==0:   return None
        if len(postorder)==1:   return TreeNode(postorder[0])
        else:
            value = postorder[len(postorder)-1]
            root=TreeNode(value)
            index = inorder.index(value)
            root.left=self.buildTree(inorder[:index], postorder[:index])
            root.right=self.buildTree((inorder[index+1:], postorder[index:len(postorder)-1]))
            return root

前序+中序确定二叉树实现:

    # 根据 前序+中序
    def buildTree2(self,preorder:List[int],inorder:List[int]):
        if len(preorder)==0:    return None
        if len(preorder)==0:    return TreeNode(preorder[0])
        else:
            value=preorder[0]
            root=TreeNode(value)
            index=inorder.index(value)
            root.left=self.buildTree2(preorder[1:index+1],inorder[:index])
            root.right=self.buildTree2(preorder[index+1:],inorder[index+1:])
            return root

测试代码:

if __name__ =="__main__":
    s=Solution()

    inorder =[9, 3, 15, 20, 7]
    postorder =[9, 15, 7, 20, 3]

    r=s.buildTree()

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值