Maximum Binary Tree

问题描述:

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;
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值