今日收获:最大二叉树,合并二叉树,二叉搜索树中的搜索,验证二叉搜索树
1. 最大二叉树
题目链接:654. - 力扣(LeetCode)
思想:和构造二叉树的思路相同,只是每次迭代都需要找最大值和所在位置。数组区间保持左闭右闭原则
方法:
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
// 根据最大值划分数组
return helper(nums,0,nums.length-1);
}
public TreeNode helper(int[] nums,int begin,int end){
if (begin>end){ // 左闭右闭
return null;
}
if (begin==end){ // 只有一个节点
return new TreeNode(nums[begin]);
}
// 寻找最大值和位置
int max=nums[begin];
int index=begin;
for (int i=begin+1;i<=end;i++){
if (nums[i]>max){
max=nums[i];
index=i;
}
}
TreeNode root=new TreeNode(max);
root.left=helper(nums,begin,index-1);
root.right=helper(nums,index+1,end);
return root;
}
}
2. 合并二叉树
题目链接:617. - 力扣(LeetCode)
思想:前序遍历合并节点,两两比较返回不为空的节点。在两个节点都不为空时计算合并节点的值并合并其左右子树
方法:
class Solution {
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;
}
// 都不为空
root2.val=root2.val+root1.val;
// 合并左右子树
root2.left=mergeTrees(root1.left,root2.left);
root2.right=mergeTrees(root1.right,root2.right);
return root2;
}
}
3. 二叉搜索树中的搜索
题目链接:700. - 力扣(LeetCode)
思想:类似于二分查找。如果当前节点值满足条件返回当前节点,小于目标值在右子树中查找,大于目标值在左子树中查找
方法:
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
if (root==null){
return null;
}
if (root.val==val){
return root;
}
if (root.val>val&&root.left!=null){
return searchBST(root.left,val);
}
if (root.val<val&&root.right!=null){
return searchBST(root.right,val);
}
return null;
}
}
4. 验证二叉搜索树
题目链接:98. - 力扣(LeetCode)
思想:
1. 可以求出二叉树的中序遍历数组,判断数组是否为递增序列;
2. 用递归法实现时,采用中序遍历,定义一个全局指针始终记录当前遍历节点的前一个节点点,然后将当前节点的值和全局指针比较。
方法:
class Solution {
TreeNode pre;
public boolean isValidBST(TreeNode root) {
if (root==null){
return true;
}
// 左子树不满足提前结束
boolean left=isValidBST(root.left);
if (left==false){
return false;
}
if (pre!=null&&root.val<=pre.val){
return false;
}
pre=root;
return isValidBST(root.right);
}
}
总结:二叉搜索树中不能有重复元素