Day17--二叉树--654. 最大二叉树,617. 合并二叉树,700. 二叉搜索树中的搜索,98. 验证二叉搜索树
654. 最大二叉树
思路:
前序遍历。寻找子数组的区间。注意区间要统一成习惯。这里是左闭右开。
java
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return build(nums, findIndexOfMaxValue(nums));
}
private TreeNode build(int[] nums, int index) {
if (nums.length == 0) {
return null;
}
if (nums.length == 1) {
return new TreeNode(nums[0]);
}
TreeNode root = new TreeNode(nums[index]);
int[] leftArray = Arrays.copyOfRange(nums, 0, index);
int[] rightArray = Arrays.copyOfRange(nums, index + 1, nums.length);
root.left = build(leftArray, findIndexOfMaxValue(leftArray));
root.right = build(rightArray, findIndexOfMaxValue(rightArray));
return root;
}
private int findIndexOfMaxValue(int[] nums) {
int max = Integer.MIN_VALUE;
int index = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] > max) {
max = nums[i];
index = i;
}
}
return index;
}
}
617. 合并二叉树
思路:
用栈迭代,前序遍历。
把node2的值加到node1上,如果一方是有节点一方是null,创建一个节点赋值为0.
java
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
// 处理null情况
if(root1==null&&root2==null){
return null;
}
if(root1==null){
return root2;
}
if(root2==null){
return root1;
}
Deque<TreeNode> stack = new ArrayDeque<>();
stack.push(root2);
stack.push(root1);
while(!stack.isEmpty()){
TreeNode node1 = stack.pop();
TreeNode node2 = stack.pop();
node1.val += node2.val;
if(node1.left==null&&node2.left!=null){
node1.left = new TreeNode(0);
}else if(node1.left!=null&&node2.left==null){
node2.left = new TreeNode(0);
}
if(node1.left!=null&&node2.left!=null){
stack.push(node2.left);
stack.push(node1.left);
}
if(node1.right==null&&node2.right!=null){
node1.right = new TreeNode(0);
}else if(node1.right!=null&&node2.right==null){
node2.right = new TreeNode(0);
}
if(node1.right!=null&&node2.right!=null){
stack.push(node2.right);
stack.push(node1.right);
}
}
return root1;
}
}
700. 二叉搜索树中的搜索
思路:
java
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
if (root == null) {
return null;
}
if (val == root.val) {
return root;
}
return searchBST(val < root.val ? root.left : root.right, val);
}
}
98. 验证二叉搜索树
思路:
中序遍历
java
class Solution {
private long prev = Long.MIN_VALUE;
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
if (!isValidBST(root.left)) {
return false;
}
if (prev >= root.val) {
return false;
}
prev = root.val;
return isValidBST(root.right);
}
}