package _06binary_tree.day20._01construct_maximum_binarytree;
import _06binary_tree.TreeNode;
public class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return traverse(nums, 0, nums.length);
}
private TreeNode traverse(int[] nums, int left, int right) {
// 递归终止条件
if (right - left < 1) return null;
if (right - left == 1) return new TreeNode(nums[0]);
// 求分割点
int maxIndex = left;
int maxValue = nums[maxIndex];
for (int i = left + 1; i < right; i++) {
if (nums[i] > maxValue) {
maxIndex = i;
maxValue = nums[i];
}
}
TreeNode root = new TreeNode(maxValue);
root.left = traverse(nums, left, maxIndex);
root.right = traverse(nums, maxIndex + 1, right);
return root;
}
}
package _06binary_tree.day20._02merge_tree;
import _06binary_tree.TreeNode;
import java.util.LinkedList;
import java.util.Queue;
public 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;
}
// 迭代(层序)
public TreeNode mergeTrees2(TreeNode root1, TreeNode root2) {
if (root1 == null) return root2;
if (root2 == null) return root1;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root1);
queue.offer(root2);
while (!queue.isEmpty()){
TreeNode node1 = queue.poll();
TreeNode node2 = queue.poll();
node1.val += node2.val;
if(node1.left != null && node2.left != null){
queue.offer(node1.left);
queue.offer(node2.left);
}
if(node1.right != null && node2.right != null){
queue.offer(node1.right);
queue.offer(node2.right);
}
if(node1.left == null){
node1.left = node2.left;
}
if(node1.right == null){
node1.right = node2.right;
}
}
return root1;
}
}
package _06binary_tree.day20._03search_bst;
import _06binary_tree.TreeNode;
public class Solution {
// 递归
public TreeNode searchBST(TreeNode root, int val) {
if (root == null || root.val == val) return root;
if (val < root.val) return searchBST(root.left, val);
if (val > root.val) return searchBST(root.right, val);
// 找不到返回null
return null;
}
// 迭代
public TreeNode searchBST2(TreeNode root, int val) {
while (root != null) {
if(val < root.val){
root = root.left;
}else if(val > root.val){
root = root.right;
}else {
return root;
}
}
return null;
}
}
package _06binary_tree.day20._04is_valid_bst;
import _06binary_tree.TreeNode;
public class Solution {
long prev = Long.MIN_VALUE;
// 递归
public boolean isValidBST(TreeNode root) {
if(root == null)return true;
if(!isValidBST(root.left))return false; // 左
if(root.val <= prev)return false; // 中
prev = root.val;
return isValidBST(root.right); // 右
}
}