java数据结构(二)4道树1道排序和搜索1道动态规划

力扣初级算法。
**

4道树的题目

**
树的类如下

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */

1.求二叉树的最大深度
递归法:


class Solution {
    public int maxDepth(TreeNode root) {
        return root == null? 0: Math.max(maxDepth(root.left),maxDepth(root.right))+1;
    }
}

非递归法,其实是利用BFS的层序遍历,要用到队列。

class Solution {
    public int maxDepth(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        if(root == null){
            return 0;
        }else{
            int level = 0;     //记录层数
            int queueSize;     //记录每层的数量
            TreeNode current;   //记录当前结点
            queue.offer(root);  //根节点入队列
            while(!queue.isEmpty()){
                level++;
                queueSize = queue.size();  //计算这层的结点数
                while(queueSize!=0){   //队列不为空可能还有结点没有遍历
                    queueSize--;      //从队列中取出队首结点
                    current = queue.peek();
                    if(current.left!=null){
                        queue.offer(current.left);
                    }
                    if(current.right!=null){
                        queue.offer(current.right);
                    }
                    queue.poll();
                }
            }
            return level;
        }
    }
}

2.验证二叉搜索树
思路:对二叉搜索树进行中序遍历的结果应该是非递减的。关键是对二叉搜索树进行非递归的中序遍历。


class Solution {
    public boolean isValidBST(TreeNode root) {
        if((root.left == null)&&(root.right == null)){
            return true;  //结点数为1的树
        }else{
            int count = 0;  //计算是第几次比较。
            TreeNode current = root; //记录中序遍历时的当前节点
            Stack<TreeNode> stack = new Stack<TreeNode>();
            int before = Integer.MIN_VALUE;  //比较的临时变量
            TreeNode lastNode = null; //用于区分某结点的左节点是否已经入过栈
            boolean result = true;  //是否为二叉搜索树结果
            stack.push(root); //根节点入栈
            while(!stack.empty()){
                if((current.left!=null)&&(lastNode!=current)){  //lastNode!=current是为了防止已经进入过栈的结点重复入栈。
                    current = current.left;
                    stack.push(current);  //入栈,找到最左下的那个结点
                }else{
                    current = stack.pop();
                    count++;  //记录比较次数
                    /*
                    	比较
                    */
                    if(count!=1){
                        if(before>=current.val){  //有一次比较出现了问题,就不是二叉搜索树。
                            result = false;
                            break;
                        }else{
                            before = current.val;
                        }
                    }else{
                        before = current.val;  //第一次不比较,只更新before,因为before初始是一个无穷小的变量。
                    }

					
                    if(current.right!=null){  //当前结点有右子树,到右节点。
                        current = current.right; 
                        stack.push(current);
                    }else{  //记录以下当前结点,防止当前结点的左子树重复入栈。
                        lastNode = current;
                    }
                }
            }
            return result;
        }
    }
}

3.判断对称二叉树,用的是双指针加递归。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        TreeNode p = root,q = root;
        return nodeEquals(p,q);
    }
    public boolean nodeEquals(TreeNode p,TreeNode q){
    	/*
    		递归的判断左右子树对称。
    		p->左子树,q->右子树。
    	*/
        if((p == null)||(q == null)){  //左右子树有一个为空
            if((p == null)&&(q == null)){
                return true;  //必须全为空才对称
            }else{
                return false;  //否则必不对称。
            }
        }else{  //左右子树均有值
            if(p.val == q.val){
            	/*
            		左子树的值等于右子树的值,才能接着判断。继续递归(左子树的左子树和右子树的右子树)和(左子树的右子树和右子树的左子树),两者均为true才是对称的,所以必须取短路与&&。
            	*/
                return nodeEquals(p.left,q.right)&&nodeEquals(p.right,q.left);
            }else{
                return false; //左子树的值不等于右子树的值,不是对称矩阵。
            }
        }
    }
}

4.二叉树的层序遍历。
和1题雷同,只能利用队列解决。

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> list2 = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        int levelSize = 0;
        if(root!=null){
            queue.offer(root);
        }   
        while(!queue.isEmpty()){
            levelSize = queue.size();
            List<Integer> list1 = new ArrayList<>();
            while(levelSize!=0){
                levelSize--;
                TreeNode current = queue.peek();
                list1.add(current.val);
                queue.poll();
                if(current.left!=null){
                    queue.offer(current.left);
                }
                if(current.right!=null){
                    queue.offer(current.right);
                }
            }
            list2.add(list1);
        }
        return list2;
    }
}

**

1道排序和搜索

**
1.合并两个有序数组
给两个有序数组,nums1[]和nums2[],里面的元素顺序均为递增,两数组大小分别为m,n。要求将nums2中的元素按顺序合并到nums1中。为便于解答,这道题已经为我们分配好了nums1的大小为m+n。
要求时间复杂度为O(m+n)。

思路:采用双指针,初始指向两数组末尾,每次把最大的数赋值给num1的末尾后移动相应指针。

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        if(m == 0){
            for(int i=0;i<n;i++){
                nums1[i] = nums2[i];
            }
        }else{
            int index1 = m-1;  //指向nums1数组的指针
            int index2 = n-1;  //指向nums2数组的指针
            int count = 1;     //这是第几次末尾赋值,用于计算末尾赋值时的数组下标。
            while((index1 > -1)&&(index2 > -1)){ //两数组全部没有遍历完毕
                if(nums1[index1]>=nums2[index2]){ //如果当前处在nums1数组的指针指向的数大于nums2数组的指针指向的数。
                    nums1[m+n-count] = nums1[index1];  //进行末尾赋值操作,将num1数组指针指向的数移动到nums1数组末尾。
                    index1--; //nums1数组指针前移
                    count++;  //末尾赋值次数加一。
                }else{  //同理,num2的数大于nums1的数。
                    nums1[m+n-count] = nums2[index2];
                    index2--;
                    count++;
                }
            }
            /*
            	最后,若nums2的数有剩余,填到nums1开头就行。
            */
            if(index2>=0){
                for(int i=0;i<=index2;i++){
                    nums1[i] = nums2[i];
                }
            }
        }
    }
}

1道动态规划

1.买卖股票的最佳时机。
给定每天的股票价格数组,求最大收益
例如[7,1,5,3,6,4],输出5.
第二天价格为1的时候买入,倒数第二天价格为6的时候卖出,收益为6-1=5.
如只能亏本,则输出0.
思路:截至至第n天的收益等于max(截止至n-1天的最大收益,第n天价格-前n-1天的最低价格)。
这里前n-1天的最低价格,我们可以用一个数组来进行记录。

class Solution {
    public int maxProfit(int[] prices) {
    	/*
    		求截止至n-1天的最低价格。
    	*/
        int[] min_price = new int[prices.length-1];  //用于记录截止至1,2,3,...n-1天的最低价格。
        for(int i=0;i<prices.length-1;i++){
            if(i == 0){
                min_price[i] = prices[0];
            }else{
                min_price[i] = Math.min(min_price[i-1],prices[i]);
            }
        }
        return getProfit(prices,min_price,prices.length-1);  //按思路中提出的公式递归计算最大收益。
    }
    public int getProfit(int[] prices,int[] min_price,int day){
    	/*
    		按思路中提出的公式递归计算最大收益。
    	*/
        if(day == 0){
            return 0;
        }else{
            return Math.max(getProfit(prices,min_price,day-1),prices[day]-min_price[day-1]);
        }
    }
}

这题刚开始不记录历史数据,会报超时的错误。
力扣的初级算法咋这么难啊。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值