前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode: 105. Construct Binary Tree from Preorder and Inorder Traversal

leetcode: 105. Construct Binary Tree from Preorder and Inorder Traversal

作者头像
JNingWei
发布2019-02-25 16:23:45
4440
发布2019-02-25 16:23:45
举报
文章被收录于专栏:JNing的专栏JNing的专栏

Difficulty

Medium.

Problem

代码语言:javascript
复制
Given preorder and inorder traversal of a tree, construct the binary tree.

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

For example, given

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

AC

代码语言:javascript
复制
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None


# DFS
class Solution():
    def buildTree(self, preorder, inorder):
        if not len(preorder):
            return None
        root = TreeNode(preorder[0])
        idx = inorder.index(root.val) # 中序中根节点的位置,左边即为左子树
        root.left = self.buildTree(preorder[1 : idx+1], inorder[ : idx])
        root.right = self.buildTree(preorder[idx+1 : ], inorder[idx+1 : ])
        return root
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年11月05日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Difficulty
  • Problem
  • AC
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档