本文主要是介绍代码随想录训练营第三十期|第二十天|二叉树part06|654.最大二叉树 ● 617.合并二叉树 ● 700.二叉搜索树中的搜索 ● 98.验证二叉搜索树,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
654. 最大二叉树 - 力扣(LeetCode)
/*** 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) {return construct(nums, 0, nums.length);}public TreeNode construct(int[] nums, int left, int right) {if (right - left < 1) return null;if (right - left == 1) return new TreeNode(nums[left]);int maxIdx = left;int max = nums[maxIdx];for (int i = left + 1; i < right; i++) {if (nums[i] > max) {max = nums[i];maxIdx = i;}} TreeNode root = new TreeNode(max);root.left = construct(nums, left, maxIdx);root.right = construct(nums, maxIdx + 1, right);return root;}
}
617. 合并二叉树 - 力扣(LeetCode)
/*** 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 mergeTrees(TreeNode root1, TreeNode root2) {if (root1 == null) return root2;if (root2 == null) return root1;root1.val += root2.val;root1.left = mergeTrees(root1.left, root2.left);root1.right = mergeTrees(root1.right, root2.right);return root1;}
}
700. 二叉搜索树中的搜索 - 力扣(LeetCode)
/*** 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 searchBST(TreeNode root, int val) {if (root == null || root.val == val) return root;if (root.val > val) return searchBST(root.left, val);if (root.val < val) return searchBST(root.right, val);return null;}
}
98. 验证二叉搜索树 - 力扣(LeetCode)
/*** 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 boolean isValidBST(TreeNode root) {if (root == null) return true;return isBST(Long.MIN_VALUE, root, Long.MAX_VALUE);}private boolean isBST(long min, TreeNode root, long max) {if (root == null) return true;if (root.val >= max || root.val <= min) return false;return isBST(min, root.left, root.val) && isBST(root.val, root.right, max);}
}
这篇关于代码随想录训练营第三十期|第二十天|二叉树part06|654.最大二叉树 ● 617.合并二叉树 ● 700.二叉搜索树中的搜索 ● 98.验证二叉搜索树的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!