654.最大二叉树
思路:递归,确定根节点,并且不断构造左右子树。从数组中找到最大值作为根节点,将数组分割为左右两部分,然后根据左右数组,去递归的构造左右子树。
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return getTree(nums, 0, nums.length);
}
public TreeNode getTree(int[] nums, int start, int end) {
if (start >= end) return null;
// 剪枝,只有一个元素的时候,直接返回
if (end - start == 1) return new TreeNode(nums[start]);
int rootIndex = getMaxIndex(nums, start, end);
TreeNode root = new TreeNode(nums[rootIndex]);
root.left = getTree(nums, start, rootIndex);
root.right = getTree(nums, rootIndex + 1, end);
return root;
}
public int getMaxIndex(int[] nums, int start, int end) { // 获取最大值所在下标
if (start >= end) return -1;
int max = nums[start];
int maxIndex = start;
for (int i = start + 1; i < end; i++) {
if (nums[i] > max) {
max = nums[i];
maxIndex = i;
}
}
return maxIndex;
}
}
617.合并二叉树
思路:前序递归遍历,根据题目条件构造节点,迭代法(层序遍历)同样可以完成。
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if (root1 == null && root2 == null) return null;
int rootVal = 0;
TreeNode left1 = null;
TreeNode left2 = null;
TreeNode right1 = null;
TreeNode right2 = null;
if (root1 != null) {
rootVal += root1.val;
left1 = root1.left;
right1 = root1.right;
}
if (root2 != null) {
rootVal += root2.val;
left2 = root2.left;
right2 = root2.right;
}
TreeNode root = new TreeNode(rootVal);
root.left = mergeTrees(left1, left2);
root.right = mergeTrees(right1, right2);
return root;
}
}
随想录中的递归方法,代码量少一半。
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.二叉搜索树中的搜索
思路:递归法和迭代法,都很简单,根据二叉搜索树的特性进行搜索即可。
递归法:
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
if (root == null) return null;
if (root.val == val) {
return root;
} else if (root.val > val) {
return searchBST(root.left, val);
} else if (root.val < val) {
return searchBST(root.right, val);
}
return null;
}
}
迭代法:
class Solution {
public TreeNode searchBST(TreeNode root, int val) { // 迭代法
while (root != null) {
if (root.val == val) return root;
if (root.val > val) {
root = root.left;
} else {
root = root.right;
}
}
return root;
}
}
98.验证二叉搜索树
思路:首先要知道,二叉搜索树的中序遍历是一个有序数组。可以对二叉搜索树进行中序遍历,将结果放入数组中,只需要判断数组是否有序即可。(递归法和迭代法都可)
class Solution {
private List<Integer> list = new ArrayList<>();
public boolean isValidBST(TreeNode root) { // 二叉搜索树中序遍历下是有序数组
inorder(root);
for (int i = 1; i < list.size(); i++) {
if (list.get(i - 1) >= list.get(i)) {
return false;
}
}
return true;
}
public void inorder(TreeNode node) {
if (node == null) return;
inorder(node.left);
list.add(node.val);
inorder(node.right);
return;
}
}