zoukankan      html  css  js  c++  java
  • Leetcode 654.最大二叉树

    最大二叉树

    给定一个不含重复元素的整数数组。一个以此数组构建的最大二叉树定义如下:

    1. 二叉树的根是数组中的最大元素。
    2. 左子树是通过数组中最大值左边部分构造出的最大二叉树。
    3. 右子树是通过数组中最大值右边部分构造出的最大二叉树。

    通过给定的数组构建最大二叉树,并且输出这个树的根节点。

    Example 1:

    输入: [3,2,1,6,0,5]

    输入: 返回下面这棵树的根节点:

     

    注意:

    1. 给定的数组的大小在 [1, 1000] 之间。

     1 public class Solution {
     2     public TreeNode constructMaximumBinaryTree(int[] nums) {
     3         return construct(nums, 0, nums.length);
     4     }
     5     public TreeNode construct(int[] nums, int l, int r) {
     6         if (l == r)
     7             return null;
     8         int max_i = max(nums, l, r);
     9         TreeNode root = new TreeNode(nums[max_i]);
    10         root.left = construct(nums, l, max_i);
    11         root.right = construct(nums, max_i + 1, r);
    12         return root;
    13     }
    14     public int max(int[] nums, int l, int r) {
    15         int max_i = l;
    16         for (int i = l; i < r; i++) {
    17             if (nums[max_i] < nums[i])
    18                 max_i = i;
    19         }
    20         return max_i;
    21     }
    22 }

  • 相关阅读:
    分析报告生产器使用问题
    如何使用分析报告生产器来生产图表
    基础数据代换代码
    浅谈Session与Cookie的区别与联系
    TCP和UDP的区别(转)
    项目管理技巧-怎么让代码规范执行下去
    吾日三省吾身
    C# 类型基础
    泛型
    事件与委托(续)
  • 原文地址:https://www.cnblogs.com/kexinxin/p/10394894.html
Copyright © 2011-2022 走看看