博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
889. Construct Binary Tree from Preorder and Postorder Traversal(python+cpp)
阅读量:3702 次
发布时间:2019-05-21

本文共 2328 字,大约阅读时间需要 7 分钟。

题目:

Return any binary tree that matches the given preorder and postorder traversals.

Values in the traversals pre and post are distinct positive integers.
Example 1:

Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1] Output: [1,2,3,4,5,6,7]

Note:

1 <= pre.length == post.length <= 30
pre[] and post[] are both permutations of 1, 2, …, pre.length.
It is guaranteed an answer exists. If there exists multiple answers, you can return any of them.

解释:

按照前序遍历和后序遍历的结果恢复二叉树,注意前序遍历和后序遍历并不能唯一地确定一颗二叉树。
python代码:

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def constructFromPrePost(self, pre, post):        """        :type pre: List[int]        :type post: List[int]        :rtype: TreeNode        """        root_val=pre[0]        root=TreeNode(root_val)        if len(pre) == 1:            return root        index=post.index(pre[1])        pre_left,post_left=pre[1:index+2],post[:index+1]        pre_right,post_right=pre[index+2:],post[index+1:-1]                if pre_left:            root.left=self.constructFromPrePost(pre_left,post_left)        if pre_right:            root.right=self.constructFromPrePost(pre_right,post_right)        return root

c++代码:

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {
public: TreeNode* constructFromPrePost(vector
& pre, vector
& post) {
int root_val=pre[0]; TreeNode* root=new TreeNode(root_val); if(pre.size()==1) return root; int idx=find(post.begin(),post.end(),pre[1])-post.begin(); vector
pre_left(pre.begin()+1,pre.begin()+idx+2); vector
post_left(post.begin(),post.begin()+idx+1); vector
pre_right(pre.begin()+idx+2,pre.end()); vector
post_right(post.begin()+idx+1,post.end()-1); if(pre_left.size()) root->left=constructFromPrePost(pre_left, post_left); if(pre_right.size()) root->right=constructFromPrePost(pre_right, post_right); return root; }};

总结:

dfs一定要学会在合适的地方判断递归条件,判断的位置合适的话,可以节省大量的时间。

转载地址:http://qglcn.baihongyu.com/

你可能感兴趣的文章
古风排版
查看>>
编译和交叉编译openssl
查看>>
编译和交叉编译curl
查看>>
ubuntu下载安装Eclipse for c/c++ developers
查看>>
Sourcetree跳过注册和git和mercurial安装
查看>>
c语言16进制字符串转字节数组
查看>>
Windows下pc-lint下载安装以及搭建环境检查Linux下开发的工程代码
查看>>
Ubuntu 16.04 LTS 升级到 Ubuntu 18.04 LTS
查看>>
ubuntu下安装CUnit出现的问题及解决
查看>>
sourcetree出现提交成功但推送失败的问题
查看>>
c语言获取本地时间
查看>>
ubuntu中openwrt编译环境的搭建
查看>>
从字符串中获取指定字符串之间字符串
查看>>
16进制字符串转字节
查看>>
Hash全解(全网最全解)
查看>>
JAVA8之Stream
查看>>
Map系列之LinkedHashMap
查看>>
Map系列之ConcurrentHashMap(JAVA8)
查看>>
浅谈RESTful接口设计和开发(增删改查)
查看>>
Mysql系列之锁机制
查看>>