在本科毕设结束后,我开始刷卡哥的“代码随想录”,每天一节。自己的总结笔记均会放在“算法刷题-代码随想录”该专栏下。
代码随想录此题链接
给定一个不重复的整数数组 nums 。 最大二叉树 可以用下面的算法从 nums 递归地构建:
创建一个根节点,其值为 nums 中的最大值。
递归地在最大值 左边 的 子数组前缀上 构建左子树。
递归地在最大值 右边 的 子数组后缀上 构建右子树。
返回 nums 构建的 最大二叉树 。
在递归构造二叉树时,在每次递归的时候不用重复切割数组,递归的时候用数组左右下标表示当前数组的范围(用来替代赋值一个新的二叉树)
此题可以使用递归遍历,
三部曲:
public TreeNode constructMaximumBinaryTree(int[] nums) {return travalBinaryTree(nums,0,nums.length);
}
//左闭右开
public TreeNode travalBinaryTree(int[] nums,int begin,int end) {if(begin + 1 == end){TreeNode cur = new TreeNode(nums[begin]);return cur;}else if(begin >= end){return null;}int maxIndex = findMaxIndex(nums,begin,end);TreeNode tree = new TreeNode(nums[maxIndex]);tree.left = travalBinaryTree(nums,begin,maxIndex);tree.right = travalBinaryTree(nums,maxIndex + 1,end);return tree;
}public int findMaxIndex(int[] nums,int begin,int end){int maxVal = nums[begin];int maxIndex = begin;for(int i = begin;i < end;i++){if(nums[i] > maxVal){maxVal = nums[i];maxIndex = i;}}return maxIndex;
}
暂无
暂无