20-算法训练营第二十天 |力扣654最大二叉树、力扣617合并二叉树、力扣98验证二叉搜索树
admin
2024-04-02 20:22:02

力扣654:最大二叉树

题目链接:力扣654:最大二叉树


思路:

1.构造二叉树一定是采用前序遍历
2.确定递归参数(nums,0,nums.length)
3.确定递归终止条件(当没有元素时或者只有一个元素)
4.确定每层递归逻辑(先找到最大值的下标,然后进行切割成左右数组递归传递下标值)


代码:

class Solution {public TreeNode constructMaximumBinaryTree(int[] nums) {return constructMaximumBinaryTree1(nums, 0, nums.length);}public TreeNode constructMaximumBinaryTree1(int[] nums, int leftIndex, int rightIndex) {if (rightIndex - leftIndex < 1) {// 没有元素了return null;}if (rightIndex - leftIndex == 1) {// 只有一个元素return new TreeNode(nums[leftIndex]);}int maxIndex = leftIndex;// 最大值所在位置int maxVal = nums[maxIndex];// 最大值for (int i = leftIndex + 1; i < rightIndex; i++) {if (nums[i] > maxVal){maxVal = nums[i];maxIndex = i;}}TreeNode root = new TreeNode(maxVal);// 根据maxIndex划分左右子树root.left = constructMaximumBinaryTree1(nums, leftIndex, maxIndex);root.right = constructMaximumBinaryTree1(nums, maxIndex + 1, rightIndex);return root;}
}

力扣617:合并二叉树

题目链接:力扣617:合并二叉树


思路:

1.递归法(前序遍历)
2.确定递归参数(跟题中一致)
3.定递归终止条件
4.确定每层递归逻辑


代码:

class Solution {public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {// 递归法(前序遍历)// 确定递归参数(跟题中一致)// 确定递归终止条件if (root1 == null) {return root2;}if (root2 == null) {return root1;}// 确定每层递归逻辑root1.val = root1.val + root2.val;root1.left = mergeTrees(root1.left, root2.left);root1.right = mergeTrees(root1.right, root2.right);return root1;}
}

力扣700:二叉搜索树中的搜索

题目链接:力扣700:二叉搜索树中的搜索


思路:

1.采用递归法(前序遍历)
2.确定递归参数(跟题中保持一致)
3.确定递归终止条件
4.确定每层递归逻辑


代码:

class Solution {public TreeNode searchBST(TreeNode root, int val) {// 采用递归法(前序遍历)// 确定递归参数(跟题中保持一致)// 确定递归终止条件TreeNode result = null;if (root == null || root.val == val) {return root;}// 确定每层递归逻辑if (root.val < val) {result = searchBST(root.right, val);}if (root.val > val) {result = searchBST(root.left, val);}return result;}
}

力扣98:验证二叉搜索树

题目链接:力扣98:验证二叉搜索树


思路:

1.定义一个指针,用于指向下一个元素
2.采用递归法(中序遍历)
3.确定递归参数,跟题中保持一致
4.确定终止条件
5.确定每层递归逻辑


代码:

class Solution {// 定义一个指针,用于指向下一个元素TreeNode pre;public boolean isValidBST(TreeNode root) {// 采用递归法(中序遍历)// 确定递归参数,跟题中保持一致// 确定终止条件if (root == null) {return true;}// 确定每层递归逻辑boolean left = isValidBST(root.left);if (pre != null && pre.val >= root.val) {return false;}pre = root;boolean right = isValidBST(root.right);return left && right;}
}

相关内容

热门资讯

中国六大天花板羊肉汤!各地招牌... 在中国美食版图里,一碗热气腾腾的羊肉汤,是跨越南北的冬日治愈美味。它不止是抚慰味蕾的烟火佳肴,更是扎...
茗聚泉城创新出圈 莒南茶企新品... 茶香汇泉城,创新焕新韵。5月29日,第二十届中国(济南)国际茶产业博览会暨第十四届茶文化节在济南茶叶...
荔枝泡酒怎么泡?内行人教你一步... 荔枝泡酒,作为一种既能满足味蕾又兼具仪式感的果酒制作方式,近年来备受关注。尤其是夏季荔枝大量上市,用...
原创 夏... 步入炎炎夏日,气温一天比一天高,很多长辈朋友都会出现吃不下饭、饭菜没滋味的情况。闷热天气里,油腻的大...