前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcod刷题(16)—— 654. 最大二叉树

Leetcod刷题(16)—— 654. 最大二叉树

作者头像
老马的编程之旅
发布2022-06-22 14:19:06
1380
发布2022-06-22 14:19:06
举报
文章被收录于专栏:深入理解Android

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

二叉树的根是数组中的最大元素。 左子树是通过数组中最大值左边部分构造出的最大二叉树。 右子树是通过数组中最大值右边部分构造出的最大二叉树。 通过给定的数组构建最大二叉树,并且输出这个树的根节点。

发现规律:这里明显使用的是前序遍历的框架,先找出根结点,然后是左子树,然后右子树

示例 :

代码语言:javascript
复制
输入:[3,2,1,6,0,5]
输出:返回下面这棵树的根节点:

      6
    /   \
   3     5
    \    / 
     2  0   
       \
        1

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

解决思路: 1.遍历一次,先求出数组中的最大值index,创建root,值为nums[index] 2.index左边的数组,再次递归进行一次操作,为root的左子树 3.index右边的数组,也是递归,作为root的右子树 4.跳出递归的条件即为start>end

代码语言:javascript
复制
class Solution {
      public static TreeNode constructMaximumBinaryTree(int[] nums) {
        if (nums == null || nums.length == 0) {
            return null;
        }
        return constructMaximumBinaryTreeSub(nums, 0, nums.length - 1);
    }

    public static TreeNode constructMaximumBinaryTreeSub(int[] nums, int start, int end) {
        if (start > end) {
            return null;
        }
        int maxIndex = getMaxIndex(start, end, nums);
        TreeNode root = new TreeNode(nums[maxIndex]);
        root.left = constructMaximumBinaryTreeSub(nums, start, maxIndex - 1);
        root.right = constructMaximumBinaryTreeSub(nums, maxIndex + 1, end);
        return root;
    }

    public static int getMaxIndex(int start, int end, int[] nums) {
        int maxIndex = start;
        for (int i = start + 1; i <= end; i++) {
            int val = nums[i];
            int maxVal = nums[maxIndex];
            if (val > maxVal) {
                maxIndex = i;
            }
        }
        return maxIndex;
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-10-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档