上好的刷题Day17

【题目1】

给你两棵二叉树: root1 和 root2 。

想象一下,当你将其中一棵覆盖到另一棵之上时,两棵树上的一些节点将会重叠(而另一些不会)。你需要将这两棵树合并成一棵新二叉树。合并的规则是:如果两个节点重叠,那么将这两个节点的值相加作为合并后节点的新值;否则,不为 null 的节点将直接作为新二叉树的节点。

返回合并后的二叉树。注意: 合并过程必须从两个树的根节点开始。

思路:把第二个数整合到第一个树上面即可

迭代法:找个数据结构记录一下两个节点,然后遍历每个节点

class Solution {
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        if(root1 == null && root2 == null)
            return null;
        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;
    }
}
class Solution {
    // 使用栈迭代
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        if (root1 == null) {
            return root2;
        }
        if (root2 == null) {
            return root1;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root2);
        stack.push(root1);
        while (!stack.isEmpty()) {
            TreeNode node1 = stack.pop();
            TreeNode node2 = stack.pop();
            node1.val += node2.val;
            if (node2.right != null && node1.right != null) {
                stack.push(node2.right);
                stack.push(node1.right);
            } else {
                if (node1.right == null) {
                    node1.right = node2.right;
                }
            }
            if (node2.left != null && node1.left != null) {
                stack.push(node2.left);
                stack.push(node1.left);
            } else {
                if (node1.left == null) {
                    node1.left = node2.left;
                }
            }
        }
        return root1;
    }
}

【二叉搜索树】

给定二叉搜索树(BST)的根节点 root 和一个整数值 val。

你需要在 BST 中找到节点值等于 val 的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 null 。

        TreeNode p = null;
        if(root == null)
            return p;
        if(root.val == val)
            return root;
        if(root.val > val)
            p =  searchBST(root.left,val);
        if(root.val < val)
            p =  searchBST(root.right,val);
        return p;
	//=========================================			
				
	while(root != null){
            if(root.val == val)
                return root;
            else if( root.val > val)
                root = root.left;
            else
                root = root.right;
            
        }
        return null;

【题目3】

给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。

有效 二叉搜索树定义如下:

节点的左子树只包含 小于 当前节点的数。
节点的右子树只包含 大于 当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。

思路:中序遍历一下,看是不是有序的就行

class Solution {
    public boolean isValidBST(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        List<Integer> list = new ArrayList<>();
        if(root == null)
            return false;
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode p = stack.peek();
            if(p != null){
                stack.pop();
                if(p.right != null)
                    stack.push(p.right);
                stack.push(p);
                stack.push(null);
                if(p.left != null)
                    stack.push(p.left); 
            }else{
                stack.pop();
                p = stack.pop();
                list.add(p.val);
            }
        }
        for(int i = 0; i<list.size()-1;i++){
            if(list.get(i) >=list.get(i+1) )
                return false;
        }
        return true;
    }
}

【题目4】!!!

给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。差值是一个正数,其数值等于两值之差的绝对值。

思路:中序遍历,则树变成数组就是有序的,所以最小的差一定在相邻的节点,记住中序前一个节点就行

class Solution {
    TreeNode pre;// 记录上一个遍历的结点
    int result = Integer.MAX_VALUE;
    public int getMinimumDifference(TreeNode root) {
       if(root==null)return 0;
       traversal(root);
       return result;
    }
    public void traversal(TreeNode root){
        if(root==null)return;
        //左
        traversal(root.left);
        //中
        if(pre!=null){
            result = Math.min(result,root.val-pre.val);
        }
        pre = root;
        //右
        traversal(root.right);
    }
}
class Solution {

    public int getMinimumDifference(TreeNode root) {
        if(root==null)
            return 0;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        TreeNode pre = null ;
        int min = Integer.MAX_VALUE;
        while(!stack.isEmpty()){
            TreeNode p = stack.peek();
            if(p!=null){
                stack.pop();
                if(p.right != null)
                    stack.push(p.right);
                stack.push(p);
                stack.push(null);
                if(p.left != null)
                    stack.push(p.left);

            }else{
                stack.pop();
                p = stack.pop();
                if(pre!=null)
                    min = Math.abs(p.val - pre.val) < min? Math.abs(p.val - pre.val): min;           
                pre = p;
            }
        }
        return min;
    }

}

【题目5】!!!

给你一个含重复值的二叉搜索树(BST)的根节点 root ,找出并返回 BST 中的所有 众数(即,出现频率最高的元素)。

如果树中有不止一个众数,可以按 任意顺序 返回。

假定 BST 满足如下定义:

结点左子树中所含节点的值 小于等于 当前节点的值
结点右子树中所含节点的值 大于等于 当前节点的值
左子树和右子树都是二叉搜索树

注意:list比数组好操作,用StreamApi进行操作

【如果是一棵普通的树】

//====================普通的树框架如下====================
class Solution {
    MyMap map = new MyMap();
    public int[] findMode(TreeNode root) {
        travesal(root);
        //排序   
    }
    public void travesal(TreeNode root){
        if(root == null)
            return;
        travesal(root.left);
        map.add(root.val,1);
        travesal(root.right);
    }
}
class MyMap extends HashMap<Integer,Integer>{
    public Integer get(Integer k){
        return containsKey(k)? super.get(k):0;
    }
    public void add(Integer k, Integer v){
        put(k,get(v)+1);
    }
}

但是,hashMap很难对value进行排序 ,转成List 用流来操作

经典永背诵

		List<Map.Entry<Integer, Integer>> mapList = map.entrySet().stream()
				.sorted((c1, c2) -> c2.getValue().compareTo(c1.getValue()))
				.collect(Collectors.toList());
		list.add(mapList.get(0).getKey());
		// 把频率最高的加入 list
		for (int i = 1; i < mapList.size(); i++) {
			if (mapList.get(i).getValue() == mapList.get(i - 1).getValue()) {
				list.add(mapList.get(i).getKey());
			} else {
				break;
			}
		}

【如果是一棵二叉搜索树】中序遍历有序的

class Solution {
    ArrayList<Integer> resList;
    int maxCount;
    int count;
    TreeNode pre;

    public int[] findMode(TreeNode root) {
        resList = new ArrayList<>();
        maxCount = 0;
        count = 0;
        pre = null;
        findMode1(root);

        return resList.stream().mapToInt(Integer::intValue).toArray();
    }

    public void findMode1(TreeNode root) {
        if (root == null) {
            return;
        }
        findMode1(root.left);

        int rootValue = root.val;
        // 计数
        if (pre == null || rootValue != pre.val) {
            count = 1;
        } else {
            count++;
        }
        // 更新结果以及maxCount
        if (count > maxCount) {
            resList.clear();
            resList.add(rootValue);
            maxCount = count;
        } else if (count == maxCount) {
            resList.add(rootValue);
        }
        pre = root;

        findMode1(root.right);
    }
}

class Solution {
    public int[] findMode(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        List<Integer> result = new ArrayList<>(); // 记录众数
        int maxCount = 0;
        int count = 0;
        stack.push(root);
        TreeNode pre = null ;
        int min = Integer.MAX_VALUE;
        while(!stack.isEmpty()){
            TreeNode p = stack.peek();
            if(p!=null){
                stack.pop();
                if(p.right != null)
                    stack.push(p.right);
                stack.push(p);
                stack.push(null);
                if(p.left != null)
                    stack.push(p.left);
            }else{
                stack.pop();
                p = stack.pop();
                // 计数
                if (pre == null || p.val != pre.val) {
                    count = 1;
                }else {
                    count++;
                }    
                // 更新结果
                if (count > maxCount) {
                    maxCount = count;
                    result.clear();
                    result.add(p.val);
                }else if (count == maxCount) {
                    result.add(p.val);
                }       
                pre = p;
            }
        }
        return result.stream().mapToInt(Integer::intValue).toArray();
    }

}

 【得出结论一个二叉搜索树的模板,中序遍历的前一个指针】

二叉树公共祖先问题详解

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值