摘要
本文主要介绍了LeetCode二叉树的几个题目,包括Day19~654.最大二叉树、617.合并二叉树、700.二叉搜索树中的搜索、98.验证二叉搜索树。
1、654.最大二叉树
1.1 思路
- 递归调用,并在递归过程中找出数组中的最大元素
- 递归结束:定义数组的开始下标和结束下标分表为start、end,如果smart > end,返回null,如果start = end,返回该节点
- 递归过程:fori循环找出数组中的最大元素下标为idx,左子树的区间为[start, idx-1],右子树的区间为[idx+1, end]
1.2 代码
public TreeNode constructMaximumBinaryTree(int[] nums) {
return doConstructMaximumBinaryTree(nums, 0, nums.length -1);
}
public TreeNode doConstructMaximumBinaryTree(int[] nums, int start, int end) {
if(start > end) {
return null;
}
if(start == end) {
return new TreeNode(nums[start]);
}
int idx = start;
for(int i=start+1; i<=end; i++) {
if(nums[i] > nums[idx]) {
idx = i;
}
}
TreeNode node = new TreeNode(nums[idx]);
node.left = doConstructMaximumBinaryTree(nums, start, idx-1);
node.right = doConstructMaximumBinaryTree(nums, idx+1, end);
return node;
}
2、617.合并二叉树
2.1 思路
- 递归模拟题
2.2 代码
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if(root1 == null && root2 == null) {
return null;
}
if(root1 != null && root2 == null) {
return root1;
}
if(root1 == null && root2 != null) {
return root2;
}
TreeNode node = new TreeNode(root1.val + root2.val);
node.left = mergeTrees(root1.left, root2.left);
node.right = mergeTrees(root1.right, root2.right);
return node;
}
3、700.二叉搜索树中的搜索
3.1 思路
- 递归遍历,二叉搜索树的特性,左子树的元素都比当前节点小,右子树的元素都比当前节点大
3.2 代码
public TreeNode searchBST(TreeNode root, int val) {
if(root == null) {
return null;
}
if(val < root.val) {
return searchBST(root.left, val);
} else if (val > root.val) {
return searchBST(root.right, val);
} else {
return root;
}
}
4、98.验证二叉搜索树
4.1 思路
- 二叉搜索树中序遍历一定是递增的,比较当前节点的值是否大于前一个节点的值
1、递归过程中如何判断二叉搜索树的元素是单调递增的?
定义变量
prev保存前一个节点,比较prev和当前节点
4.2 代码
TreeNode prev;
// 二叉搜索树中序遍历一定是递增的,比较当前节点的值是否大于前一个节点的值
public boolean isValidBST(TreeNode root) {
if(root == null) {
return true;
}
boolean left = isValidBST(root.left);
if(left == false) {
return false;
}
if(prev != null && root.val <= prev.val) {
return false;
}
prev = root;
boolean right = isValidBST(root.right);
return left && right;
}