package LeetCode.Treepart06;
/**
* 654. 最大二叉树
* 给定一个不重复的整数数组nums 。最大二叉树可以用下面的算法从nums 递归地构建:
* 创建一个根节点,其值为nums 中的最大值。
* 递归地在最大值左边的子数组前缀上构建左子树。
* 递归地在最大值 右边 的子数组后缀上构建右子树。
* 返回nums 构建的 最大二叉树 。
* */
public class MaximumBinaryTree_654 {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return constructMaximumBinaryTree1(nums, 0, nums.length);
}
public TreeNode constructMaximumBinaryTree1(int[] nums, int leftIndex, int rightIndex) {
if (rightIndex - leftIndex < 1) {// 没有元素了
return null;
}
if (rightIndex - leftIndex == 1) {// 只有一个元素
return new TreeNode(nums[leftIndex]);
}
int maxIndex = leftIndex;// 最大值所在位置
int maxVal = nums[maxIndex];// 最大值
for (int i = leftIndex + 1; i < rightIndex; i++) {
if (nums[i] > maxVal){
maxVal = nums[i];
maxIndex = i;
}
}
TreeNode root = new TreeNode(maxVal);
// 根据maxIndex划分左右子树
root.left = constructMaximumBinaryTree1(nums, leftIndex, maxIndex);
root.right = constructMaximumBinaryTree1(nums, maxIndex + 1, rightIndex);
return root;
}
}
package LeetCode.Treepart06;
/**
* 617. 合并二叉树
* 给你两棵二叉树: root1 和 root2 。
* 想象一下,当你将其中一棵覆盖到另一棵之上时,两棵树上的一些节点将会重叠(而另一些不会)。
* 你需要将这两棵树合并成一棵新二叉树。合并的规则是:如果两个节点重叠,那么将这两个节点的值相加作为合并后节点的新值;否则,不为 null 的节点将直接作为新二叉树的节点。
* 返回合并后的二叉树。
* 注意: 合并过程必须从两个树的根节点开始。
* */
public class MergeTwoBinaryTrees_617 {
// 递归
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;
}
}
package LeetCode.Treepart06;
/**
* 700. 二叉搜索树中的搜索
* 给定二叉搜索树(BST)的根节点root和一个整数值val。
* 你需要在 BST 中找到节点值等于val的节点。 返回以该节点为根的子树。
* 如果节点不存在,则返回null。
* */
public class SearchinBinarySearchTree_700 {
// 递归,普通二叉树
public TreeNode searchBST(TreeNode root, int val) {
if (root == null || root.val == val) {
return root;
}
TreeNode left = searchBST(root.left, val);
if (left != null) {
return left;
}
return searchBST(root.right, val);
}
}
package LeetCode.Treepart06;
import java.util.Stack;
/**
* 98. 验证二叉搜索树
* 给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。
* 有效 二叉搜索树定义如下:
* 节点的左子树只包含 小于 当前节点的数。
* 节点的右子树只包含 大于 当前节点的数。
* 所有左子树和右子树自身必须也是二叉搜索树。
* */
public class ValidateBinarySearchTree_98 {
public boolean isValidBST(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
TreeNode pre = null;
if(root != null)
stack.add(root);
while(!stack.isEmpty()){
TreeNode curr = stack.peek();
if(curr != null){
stack.pop();
if(curr.right != null)
stack.add(curr.right);
stack.add(curr);
stack.add(null);
if(curr.left != null)
stack.add(curr.left);
}else{
stack.pop();
TreeNode temp = stack.pop();
if(pre != null && pre.val >= temp.val)
return false;
pre = temp;
}
}
return true;
}
}