• 力扣:654. 最大二叉树


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

    1. package com.算法专练.力扣.最大二叉树;
    2. import java.util.Arrays;
    3. /**
    4. * @author xnl
    5. * @Description:
    6. * @date: 2022/8/20 22:05
    7. */
    8. public class Solution {
    9. public static void main(String[] args) {
    10. Solution solution = new Solution();
    11. int[] arr = {3,2,1,6,0,5};
    12. System.out.println(solution.constructMaximumBinaryTree(arr));
    13. }
    14. public TreeNode constructMaximumBinaryTree(int[] nums) {
    15. if (nums == null || nums.length ==0){
    16. return null;
    17. }
    18. int maxIndex = 0;
    19. int maxValue = nums[0];
    20. for (int i = 1; i < nums.length; i++){
    21. if (nums[i] > maxValue){
    22. maxValue = nums[i];
    23. maxIndex = i;
    24. }
    25. }
    26. TreeNode node = new TreeNode(maxValue);
    27. node.left = constructMaximumBinaryTree(Arrays.copyOfRange(nums, 0, maxIndex));
    28. node.right = constructMaximumBinaryTree(Arrays.copyOfRange(nums, maxIndex + 1, nums.length));
    29. return node;
    30. }
    31. }
    32. class TreeNode {
    33. int val;
    34. TreeNode left;
    35. TreeNode right;
    36. TreeNode() {}
    37. TreeNode(int val) { this.val = val; }
    38. TreeNode(int val, TreeNode left, TreeNode right) {
    39. this.val = val;
    40. this.left = left;
    41. this.right = right;
    42. }
    43. }

    单调栈解法

    1. /**
    2. * Definition for a binary tree node.
    3. * public class TreeNode {
    4. * int val;
    5. * TreeNode left;
    6. * TreeNode right;
    7. * TreeNode() {}
    8. * TreeNode(int val) { this.val = val; }
    9. * TreeNode(int val, TreeNode left, TreeNode right) {
    10. * this.val = val;
    11. * this.left = left;
    12. * this.right = right;
    13. * }
    14. * }
    15. */
    16. class Solution {
    17. public TreeNode constructMaximumBinaryTree(int[] nums) {
    18. Deque deque = new ArrayDeque<>();
    19. for (int i = 0; i < nums.length; i++){
    20. TreeNode node = new TreeNode(nums[i]);
    21. while (!deque.isEmpty()){
    22. TreeNode top = deque.peek();
    23. if (top.val > node.val){
    24. deque.push(node);
    25. top.right = node;
    26. break;
    27. }
    28. node.left = deque.poll();
    29. }
    30. if (deque.isEmpty()) deque.push(node);
    31. }
    32. return deque.peekLast();
    33. }
    34. }

  • 相关阅读:
    ASP.NET第五章 Application、Session和Cookie对象
    Mybatis查询结果处理
    AI应用开发之路-准备:发起一个开源小项目 DashScope SDK for .NET
    mysql 练习1
    SOLR分组聚合的相关技巧
    Docker 常用命令整理
    .NET GC
    Python二级 每周练习题19
    耐蚀点蚀镀铜工艺
    重温JS——(ES6)异步编程(promise对象、async函数)
  • 原文地址:https://blog.csdn.net/newOneObject/article/details/126445259