【剑指OFFER-二刷】

反转链表

输入一个链表,反转链表后,输出链表的所有元素。

不借助任何多余空间,代码如下:

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

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head == null)
            return null;

        ListNode left = head;
        ListNode current = head;
        ListNode right = head.next;

        while(current.next != null) {
            current.next = right.next;
            right.next = left;
            left = right;
            right = current.next;
        }
        return left;
    }
}

重建二叉树

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

一定要注意确定前后界限,可以用个例子去试。

/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        if(pre == null || in == null)
            return null;

        return reConstructBinaryTree(pre, in, 0, pre.length, 0, in.length);
    }
    public TreeNode reConstructBinaryTree(int[] pre, int[] in, int preS, int preE, int inS, int inE) {
        if(preE <= preS || inE <= inS)
            return null;

        int i = inS;
        int count = 0;
        for(; i < inE && in[i] != pre[preS]; i++) {count++;}

        TreeNode root = new TreeNode(pre[preS]);
        root.left = reConstructBinaryTree(pre, in, preS+1, preS+1+count, inS, inS+count);
        root.right = reConstructBinaryTree(pre, in, preS+1+count, preE, inS+count+1, inE);

        return root;
    }
}

你可能感兴趣的:(【剑指OFFER-二刷】)