力扣---2020.5.10

236. 二叉树的最近公共祖先

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null || root==p || root==q){
            return root;
        }
        TreeNode left = lowestCommonAncestor(root.left,p,q);
        TreeNode right = lowestCommonAncestor(root.right,p,q);
        if(left !=null && right != null){
            return root;
        }else if(left != null){
            return left;
        }else if(right != null){
            return right;
        }
        return null;
    }
}

25. K 个一组翻转链表

class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head==null) return head;
        ListNode a,b;
        a=b=head;
        for(int i = 0;i<k;i++){
            if(b==null) return head;
            b = b.next;
        }

        ListNode newHead = reverse(a,b);
        a.next = reverseKGroup(b,k);
        return newHead;
    }

    /** 反转区间 [a, b) 的元素,注意是左闭右开 */
    ListNode reverse(ListNode a, ListNode b) {
        ListNode pre, cur;
        pre = null; cur = a; 
        // while 终止的条件改一下就行了
        while (cur != b) {
            ListNode nxt = cur.next;
            cur.next = pre;
            pre = cur;
            cur = nxt;
        }
        // 返回反转后的头结点
        return pre;
    }
}

你知道的越多,你不知道的越多。

你可能感兴趣的:(数据结构与算法)