LeetCode C++ 106. Construct Binary Tree from Inorder and Postorder Traversal【Tree/分治】中等
发布日期:2021-07-01 02:52:16
浏览次数:3
分类:技术文章
本文共 1498 字,大约阅读时间需要 4 分钟。
Given inorder and postorder traversal of a tree, construct the binary tree.
Note: You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7]postorder = [9,15,7,20,3]
Return the following binary tree:
3 / \ 9 20 / \ 15 7
题意:根据一棵树的中序遍历与后序遍历构造二叉树。可以假设树中没有重复的元素。
思路
简单的分治题目,递归解决。代码如下:
/** * 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* buildTree(vector & inorder, vector & postorder) { return rebuild(0, inorder.size() - 1, 0, postorder.size() - 1, inorder, postorder); } TreeNode* rebuild(int leftin, int rightin, int leftpost, int rightpost, vector & inorder, vector & postorder) { if (leftin > rightin || leftpost > rightpost) return nullptr; TreeNode *root = new TreeNode(postorder[rightpost]); int rootin = leftin; while (rootin <= rightin && inorder[rootin] != postorder[rightpost]) ++rootin; int leftsize = rootin - leftin; root->left = rebuild(leftin, rootin - 1, leftpost, leftpost + leftsize - 1, inorder, postorder); root->right = rebuild(rootin + 1, rightin, leftpost + leftsize, rightpost - 1, inorder, postorder); return root; }};
效率如下:
执行用时:52 ms, 在所有 C++ 提交中击败了26.98% 的用户内存消耗:16.9 MB, 在所有 C++ 提交中击败了85.71% 的用户
转载地址:https://memcpy0.blog.csdn.net/article/details/108806945 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
不错!
[***.144.177.141]2024年04月19日 10时54分46秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
java.net.BindException: 无法指定被请求的地址
2019-05-01
scala list
2019-05-01
svn服务器安装
2019-05-01
spark 笔记1
2019-05-01
shell dirname basename
2019-05-01
未来已至,5G加持下的云游戏将走向何方?
2019-05-01
计算机网络 —— 网络层 1.
2019-05-01
Android 之 ContentProvider 与 ContentResolver
2019-05-01
【接口自动化】
2019-05-01
推荐一位川大零基础转行 Python 的人生勇士
2019-05-01
Python解惑之:True与False
2019-05-01
你要的微信小程序终于来了
2019-05-01
有了这些 Chrome 插件,效率提升10倍(建议收藏)
2019-05-01
Python 开发者都会遇到的错误:UnboundLocalError
2019-05-01
只有1%的程序员搞懂过浮点数陷阱
2019-05-01
一名 Google 工程师的大数据处理经验
2019-05-01
命名难,难于上青天
2019-05-01
没钱没公司,怎么做一款付费产品
2019-05-01
代码整洁之道-编写 Pythonic 代码
2019-05-01