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 }

  • 相关阅读:
    return关键字
    类的成员之二 :方法
    面向对象(一)
    正则表达式(一)
    Linux FTP服务器vsftpd介绍与软件包安装
    Linux SSH
    Linux telnet
    Linux firewalld
    Linux iptables nat表的使用
    Linux iptables规则的基本使用
  • 原文地址:https://www.cnblogs.com/kexinxin/p/10394894.html
Copyright © 2011-2022 走看看