leetcode 654. Maximum Binary Tree

1.题目

Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
给一个不含重复元素的整型数组。要求构造一棵二叉树,规则为:
1)根结点是数组中最大的元素
2)最大元素左侧的元素构成左子树,右侧的元素构成右子树
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

2.分析

1.递归

用递归求解比较容易理解。
找出数组中最大值,作为根结点
根结点的左子节点为左侧最大值,右子节点为右侧最大值。递归求解即可。

2.栈

这个数组对应唯一的一棵树,数组中的元素其实是树的中序遍历。通过栈和根结点的特点可以将这棵树还原出来。

stack s 存储树节点
cur 遍历的当前元素

遍历数组:
当s不为空 且 栈顶节点值小于当前节点值
cur->left = s.top()->left

如果栈顶节点大于当前节点值,则
s.top()->right = cur

当前节点入栈

最终,栈底元素为树的根结点

3.代码

递归

TreeNode* constructMaximumBinaryTree3(vector<int>& nums) {
    return buildTree(nums, 0, nums.size() - 1);
}
TreeNode* buildTree(vector<int>& nums, int left, int right) {
    if (left < right)
        return NULL;
    int idx = left;
    for (int i = left; i <= right; i++)
        idx = nums[i] > nums[idx] ? i : idx;
    TreeNode* root = new TreeNode(nums[idx]);
    root->left = buildTree(nums, left, idx - 1);
    root->right = buildTree(nums, idx + 1, right);
    return root;
}

class Solution {
public:
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        stack<TreeNode*> s;
        for (int i = 0; i < nums.size(); i++) {
            TreeNode* cur = new TreeNode(nums[i]);
            while (!s.empty() && s.top()->val < nums[i]) {
                cur->left = s.top();
                s.pop();
            }
            if (!s.empty())
                s.top()->right = cur;
            s.push(cur);
        }
        TreeNode* root;
        while(!s.empty()){
            root = s.top();
            s.pop();
        }
        return root;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值