LeetCode刷题(C++)——Construct Binary Tree from Inorder and Postorder Traversal(Normal)
来源:互联网 发布:大麦户源码安装教程 编辑:程序博客网 时间:2024/06/05 09:22
题目描述
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
/** * 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<int>& inorder, vector<int>& postorder) { if (inorder.size() == 0 || postorder.size() == 0 || inorder.size() != postorder.size())return NULL;return dfs(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1);}TreeNode* dfs(vector<int>&inorder, int l1, int r1, vector<int>& postorder, int l2, int r2){if (l2 > r2)return NULL;if (l2 == r2)return new TreeNode(postorder[r2]);TreeNode* root = new TreeNode(postorder[r2]);for (int i = 0; i < inorder.size();i++){if (inorder[i] == postorder[r2]){root->left = dfs(inorder, l1, i - 1, postorder, l2, l2 + i - l1-1);root->right = dfs(inorder, i + 1, r1, postorder, l2 + i - l1, r2 - 1);return root;}}return NULL; }};
1 0
- LeetCode刷题(C++)——Construct Binary Tree from Inorder and Postorder Traversal(Normal)
- LeetCode刷题(C++)——Construct Binary Tree from Preorder and Inorder Traversal(Normal)
- LeetCode106—Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal(medium)
- *(leetcode) Construct Binary Tree from Inorder and Postorder Traversal (tree)
- LeetCode[Tree]: Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode]Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode] Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal
- [Leetcode] Construct Binary Tree from Inorder and Postorder Traversal
- leetcode 110: Construct Binary Tree from Inorder and Postorder Traversal
- 【leetcode】Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode]Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode]Construct Binary Tree from Inorder and Postorder Traversal
- AOJ.859 地毯填补问题 (递归与分治)
- 安装maven遇到的问题
- Tensorflow实现最近邻
- 判断一棵树是不是二叉搜索树
- xCode8 ios10再次开发记录
- LeetCode刷题(C++)——Construct Binary Tree from Inorder and Postorder Traversal(Normal)
- 第二章 递归
- CSDN日报20170428 ——《你的开发为何如此低效?》
- 网络层-ICMP(互联网消息控制协议)
- Linux基础学习笔记之screen命令
- 关于三级管总结
- 作业优先调度算法 先来先服务、短作业调度算法(c语言描述)
- Tensorflow实现多层感知器
- Python机器学习库SKLearn分类算法之朴素贝叶斯