力扣:654. 最大二叉树

其实只需要每一次遍历的时候,找到最大的数组下标就行了。然后遍历既可以得到结果

package com.算法专练.力扣.最大二叉树;

import java.util.Arrays;

/**
 * @author xnl
 * @Description:
 * @date: 2022/8/20   22:05
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] arr = {3,2,1,6,0,5};
        System.out.println(solution.constructMaximumBinaryTree(arr));
    }

    public TreeNode constructMaximumBinaryTree(int[] nums) {
        if (nums == null || nums.length ==0){
            return null;
        }
        int maxIndex = 0;
        int maxValue = nums[0];
        for (int i = 1; i < nums.length; i++){
            if (nums[i] > maxValue){
                maxValue = nums[i];
                maxIndex = i;
            }
        }
        TreeNode node = new TreeNode(maxValue);
        node.left = constructMaximumBinaryTree(Arrays.copyOfRange(nums, 0, maxIndex));
        node.right = constructMaximumBinaryTree(Arrays.copyOfRange(nums, maxIndex + 1, nums.length));
        return node;
    }
}

class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }

单调栈解法

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        Deque<TreeNode> deque = new ArrayDeque<>();
        for (int i = 0; i < nums.length; i++){
            TreeNode node = new TreeNode(nums[i]);
            while (!deque.isEmpty()){
                TreeNode top = deque.peek(); 
                if (top.val > node.val){
                    deque.push(node);
                    top.right = node;
                    break;
                }
                node.left = deque.poll();
            }
            if (deque.isEmpty()) deque.push(node);
        }
        return deque.peekLast();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值