654.最大二叉树
构造树一般采用的是前序遍历
确定终止条件 :
题目中说了输入的数组大小一定是大于等于1的,所以我们不用考虑小于1的情况,那么当递归遍历的时候,如果传入的数组大小为1,说明遍历到了叶子节点了
题目链接/文章讲解:代码随想录
视频讲解:又是构造二叉树,又有很多坑!| LeetCode:654.最大二叉树_哔哩哔哩_bilibili
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
if (nums.length == 1) {
return new TreeNode(nums[0]);
}
int maxValue = 0, index = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] > maxValue) {
maxValue = nums[i];
index = i;
}
}
TreeNode root = new TreeNode(maxValue);
if (index > 0) {
int leftArray[] = Arrays.copyOfRange(nums, 0, index);
root.left = constructMaximumBinaryTree(leftArray);
}
if (index < nums.length - 1) {
int rightArray[] = Arrays.copyOfRange(nums, index + 1, nums.length);
root.right = constructMaximumBinaryTree(rightArray);
}
return root;
}
}
617.合并二叉树
构造树一般采用的是前序遍历
题目链接/文章讲解:代码随想录
视频讲解:一起操作两个二叉树?有点懵!| LeetCode:617.合并二叉树_哔哩哔哩_bilibili
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:700.二叉搜索树中的搜索_哔哩哔哩_bilibili
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
if (root == null) return null;
if (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:98.验证二叉搜索树_哔哩哔哩_bilibili
class Solution {
public boolean isValidBST(TreeNode root) {
return helper(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private boolean helper(TreeNode root, long left, long right) {
if (root == null) {
return true;
}
long cur = root.val;
return left < cur && cur < right && helper(root.left, left , cur) && helper(root.right, cur, right);
}
}