Maximum Binary Tree

来源:互联网 发布:淘宝买家好评率 编辑:程序博客网 时间:2024/06/06 13:14

问题描述:

Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
1. The root is the maximum number in the array.
2. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
3. 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.

思路分析:

本题目要求构造的最大二叉树是指:根节点的值是数组中最大数,左节点的值是根节点左边的数组中最大数,右节点的值是根节点右边的数组中最大数;因此,我们可以将问题分为以下三种情况:
1. 数组没有任何元素,则直接返回NULL;
2. 数组只有一个元素,则构造只有一个节点的最大树;
3. 数组的元素超过1个,则先找出数组的最大数max,然后将max左边和右边的数分别push到left和right容器中,递归调用constructMaximumBinaryTree函数,找到left和right容器的最大数,构造起根节点的leftNode和rightNode。

代码实现:

/** * 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* constructMaximumBinaryTree(vector<int>& nums) {        if (nums.size() == 0)            return NULL;        else if (nums.size() == 1) {            TreeNode* node = new TreeNode(nums[0]);            node->left = NULL;            node->right = NULL;            return node;        }        else if (nums.size() > 1) {            int max = nums[0], index = 0;            for (int i = 0; i <= nums.size()-1; i++) {                if (max < nums[i]) {                    max = nums[i];                    index = i;                }            }            TreeNode* node = new TreeNode(max);     //找到最大数max,并建立根节点            vector<int> left, right;            for (int i = 0; i < index; i++) {                left.push_back(nums[i]);        //最大数左边的节点都放在left            }            for (int j = index + 1; j < nums.size(); j++) {                right.push_back(nums[j]);       //最大数右边的节点都放在right            }            TreeNode* leftNode = constructMaximumBinaryTree(left);      //递归函数,建立左右节点            TreeNode* rightNode = constructMaximumBinaryTree(right);            node->left = leftNode;            node->right = rightNode;            return node;        }    }};
原创粉丝点击