LeetCode#654 Maximum Binary Tree (week12)
来源:互联网 发布:淘宝店已下架什么意思 编辑:程序博客网 时间:2024/05/18 01:33
week12
题目
Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
The root is the maximum number in the array.
The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.
Construct the maximum tree by the given array and output the root node of this tree.
Example 1:
Input: [3,2,1,6,0,5]
Output: return the tree root node representing the following tree:
原题地址:https://leetcode.com/problems/maximum-binary-tree/description/
解析
题目要求将给定数组中的最大元素作为二叉树的根节点,其中左子树由该最大元素左边的元素构成,右子树由该最大元素右边的元素构成,左子树的根节点为该子树中的最大元素,以此类推。
大致思路为对于给定数组,选出其最大元素作为根节点,将最大元素左边的元素和右边的元素分别构造成新的数组,对这两个数组递归使用上述过程。
代码
class Solution {public: TreeNode* constructMaximumBinaryTree(vector<int>& nums) { if (nums.size() == 0) { return NULL; } TreeNode *root = new TreeNode(0); constructTree(nums, root); return root; } void constructTree(vector<int>& nums, TreeNode *root) { int index, largest; findMax(nums, index, largest); /* 将当前数组中最大的元素作为根节点 */ root->val = largest; vector<int> leftTree; vector<int> rightTree; /* 递归调用,用最大元素左边的元素构造左子树 */ for (int i = 0; i < index; ++i) { leftTree.push_back(nums[i]); } if (leftTree.size() > 0) { root->left = new TreeNode(0); constructTree(leftTree, root->left); } /* 递归调用,用最大元素右边的元素构造右子树 */ for (int i = index + 1; i < nums.size(); ++i) { rightTree.push_back(nums[i]); } if (rightTree.size() > 0) { root->right = new TreeNode(0); constructTree(rightTree, root->right); } } /* 找到当前数组中的最大元素 */ void findMax(vector<int>& nums, int &index, int &largest) { if (nums.size() != 0) { int tmp = nums[0]; index = 0; for (int i = 0; i < nums.size(); ++i) { if (nums[i] > tmp) { tmp = nums[i]; index = i; } } largest = tmp; } }};
- LeetCode#654 Maximum Binary Tree (week12)
- LeetCode Maximum Binary Tree
- leetcode 654 Maximum Binary Tree C++
- LeetCode 654 Maximum Binary Tree(递归)
- leetcode 654. Maximum Binary Tree
- 【LeetCode】654. Maximum Binary Tree
- [LeetCode]654. Maximum Binary Tree
- leetcode 654. Maximum Binary Tree
- leetcode 654. Maximum Binary Tree
- Leetcode: 654. Maximum Binary Tree
- LeetCode 654. Maximum Binary Tree
- [LeetCode] 654. Maximum Binary Tree
- [leetcode] 654. Maximum Binary Tree
- [LeetCode] 654. Maximum Binary Tree
- Leetcode - Tree - Maximum Depth of Binary Tree
- *****(leetcode) Binary Tree Maximum Path Sum (tree)
- [leetcode][tree] Maximum Depth of Binary Tree
- LeetCode 654 Maximum Binary Tree(构建二叉搜索树)
- c++网络编程服务器
- LeetCode-485. Max Consecutive Ones
- Caffe学习笔记7--自定义layer的实现
- SSM(Spring+SpringMVC+Mybatis)框架搭建
- mysql主从同步错误恢复
- LeetCode#654 Maximum Binary Tree (week12)
- Java中static和final用法
- HDOJ Wash JAVA超时 6000
- scikit-learn 中文文档-高斯过程-监督学习|ApacheCN
- UVA 11374 SPFA+路径打印
- 人工智能学习清单
- POJ 1129.Channel Allocation
- 两种快速排序的实现(C语言)
- Leetcode 113. Path Sum II