判断回文&&单链表的排序&&平衡二叉树

190 阅读1分钟

NC141 判断回文

题目链接

1、解题思路

使用双指针,左右两边靠拢。

2、代码
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 
     * @param str string字符串 待判断的字符串
     * @return bool布尔型
     */
    public boolean judge (String str) {
        // write code here
        int l = 0;
        int r = str.length() - 1;
        while(l <= r){
            if(str.charAt(l) != str.charAt(r)){
                return false;
            }
            l++;
            r--;
        }
        return true;
    }
}

NC70 单链表的排序

题目链接

1、解题思路

这个题目的很多种解法,我写了一种插入排序。就是每次让新的节点插入一个有序的链表。

2、代码
import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 the head node
     * @return ListNode类
     */
    private void insert(ListNode dummy, ListNode node) {
        ListNode temp = dummy;
        while (temp.next != null) {
            if (temp.val <= node.val && node.val <= temp.next.val) {
                node.next = temp.next;
                temp.next = node;
                return;
            }
            temp = temp.next;
        }
        temp.next = node;
    }

    public ListNode sortInList(ListNode head) {
        // write code here
        ListNode dummy = new ListNode(Integer.MIN_VALUE);
        ListNode temp = head;
        while (temp != null) {
            ListNode node = temp.next;
            temp.next = null;
            insert(dummy, temp);
            temp = node;
        }
        return dummy.next;
    }
}

NC62 平衡二叉树

题目链接

1、解题思路

首先,定义一个函数求树的高度,递归就可以解决。其次,左子树和右子树高度只差小于1,并且左子树和右子树都是一颗平衡二叉树,这个时候的树才是一颗平衡树。

2、代码
public class Solution {
    private int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftH = getHeight(root.left);
        int rightH = getHeight(root.right);
        return leftH > rightH ? leftH + 1 : rightH + 1;
    }

    public boolean IsBalanced_Solution(TreeNode root) {
        if (root == null) {
            return true;
        }
        int leftH = getHeight(root.left);
        int rightH = getHeight(root.right);
        int gap = leftH > rightH ? leftH - rightH : rightH - leftH;
        if (gap > 1) {
            return false;
        } else {
            return IsBalanced_Solution(root.right) && IsBalanced_Solution(root.left);
        }
    }
}