LeetCode 654. Maximum Binary Tree
来源:互联网 发布:淘宝首页在线制作 编辑:程序博客网 时间:2024/06/06 02:03
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:
6/ \3 5\ / 2 0 \ 1
Note:
The size of the given array will be in the range [1,1000].
题目的意思是给定一个非序列,用此序列建树,其中根结点的值为序列中最大的数,最大数的左侧为左子树节点,右侧为右子树节点。
考察递归。
/** * 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: int find_max_idx(vector<int>& nums, int start, int end) { if(start==end) return -1; int max_index=start; for(int i=start;i<end;++i) { max_index = nums[max_index] > nums[i]?max_index:i; } return max_index; } TreeNode* buildTree(vector<int>& nums, int start, int end) { TreeNode *root=nullptr; int father = find_max_idx(nums,start,end); if(father==-1) return nullptr; root = new TreeNode(nums[father]); root->left = buildTree(nums, start, father); root->right = buildTree(nums, father+1, end); return root; } TreeNode* constructMaximumBinaryTree(vector<int>& nums) { return buildTree(nums,0,nums.size()); }};
阅读全文
0 0
- 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 Maximum Binary Tree
- 654. Maximum Binary Tree
- 654. Maximum Binary Tree
- 654. Maximum Binary Tree
- 654. Maximum Binary Tree
- 654. Maximum Binary Tree
- 654. Maximum Binary Tree
- 654. Maximum Binary Tree
- UVA 12034 Race
- 查询及删除重复记录的SQL语句
- 20171103
- 阿里云的OSS对象存储 java
- 三齿轮问题:三个齿轮啮合
- LeetCode 654. Maximum Binary Tree
- 经典排序算法
- bzoj1049 [HAOI2006]数字序列 ( LIS + 区间DP)
- SpringBoot自动配置的实现原理
- 前序 中序 后序遍历
- 项目管理心得:一个项目经理的个人体会、经验总结
- 爆搜dfs
- Scikit-learn安装教程
- 我为什么喜欢跑步