剑指offer-第一部分

01 二维数组中的查找

题目描述

在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

解法:利用左下角的数a作为起点,(因为如果大于a的话就往右走,如果小于a的话,就往上走)一直这样判断,知道行数=1或列数达到最大值。

代码:

​
public class Solution {
    public boolean Find(int target, int [][] array) {
         boolean a1=false;
         for(int i=0;i<array.length;i++){
        	 for(int j=0;j<array[i].length;j++){
        		 if(array[i][j]==target){
        			 a1=true;
        			 break;
        		 }
        		
        	 }
         }
         return a1;
    }
}

​
public class Solution {
    public boolean Find(int [][] array,int target) {
        int row=0;
        int col=array[0].length-1;
        while(row<=array.length-1&&col>=0){
            if(target==array[row][col])
                return true;
            else if(target>array[row][col])
                row++;
            else
                col--;
        }
        return false;
 
    }
}

02替换空格

题目描述

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

解法:

从前往后替换,后面的字符要不断往后移动,要多次移动,所以效率低下

 从后往前,先计算需要多少空间,然后从后往前移动,则每个字符只为移动一次,这样效率更高一点。

代码:

public class Solution {
    public String replaceSpace(StringBuffer str) {
        int spacenum = 0;//spacenum为计算空格数
        for(int i=0;i<str.length();i++){
            if(str.charAt(i)==' ')
                spacenum++;
        }
        int indexold = str.length()-1; //indexold为为替换前的str下标
        int newlength = str.length() + spacenum*2;//计算空格转换成%20之后的str长度
        int indexnew = newlength-1;//indexold为为把空格替换为%20后的str下标
        str.setLength(newlength);//使str的长度扩大到转换成%20之后的长度,防止下标越界
        for(;indexold>=0 && indexold<newlength;--indexold){ 
                if(str.charAt(indexold) == ' '){  //
                str.setCharAt(indexnew--, '0');
                str.setCharAt(indexnew--, '2');
                str.setCharAt(indexnew--, '%');
                }else{
                    str.setCharAt(indexnew--, str.charAt(indexold));
                }
        }
        return str.toString();
    }
}

03从尾到头打印链表

题目描述

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

解法:利用栈先进后出的特点。

 public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
import java.util.Stack;
import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        
        Stack<Integer> stack=new Stack<Integer>();
        while(listNode!=null){
            stack.push(listNode.val);
            listNode=listNode.next;     
        }
        
        ArrayList<Integer> list=new ArrayList<Integer>();
        while(!stack.isEmpty()){
            list.add(stack.pop());
        }
        return list;
    
    }
}

04重建二叉树

题目描述

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

解法:递归:比如利用前序遍历中的第一个是根节点划分中序遍历为{4,7,2}{5,3,8,6}

                                   前序遍历变为{2,4,7},{3,5,6,8}

                                  再一次递归调用方法递归左子树,右子树。

代码:

/**
 * 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) {
        TreeNode root=reConstructBinaryTree(pre,0,pre.length-1,in,0,in.length-1);
        return root;
    }
    private TreeNode reConstructBinaryTree(int [] pre,int startPre,int endPre,int [] in,int startIn,int endIn) {
         
        if(startPre>endPre||startIn>endIn)
            return null;
        TreeNode root=new TreeNode(pre[startPre]);
         
        for(int i=startIn;i<=endIn;i++)
            if(in[i]==pre[startPre]){
                root.left=reConstructBinaryTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1);
                root.right=reConstructBinaryTree(pre,i-startIn+startPre+1,endPre,in,i+1,endIn);
                      break;
            }
                 
        return root;
    }
}

 

题目描述 
根据中序遍历和后序遍历构造二叉树

public TreeNode buildTree(int[] inorder, int[] postorder) {
    int inStart = 0;
    int inEnd = inorder.length - 1;
    int postStart = 0;
    int postEnd = postorder.length - 1;

    return buildTree(inorder, inStart, inEnd, postorder, postStart, postEnd);
}

public TreeNode buildTree(int[] inorder, int inStart, int inEnd,
        int[] postorder, int postStart, int postEnd) {
    if (inStart > inEnd || postStart > postEnd)
        return null;

    int rootValue = postorder[postEnd];
    TreeNode root = new TreeNode(rootValue);

    int k = 0;
    for (int i = 0; i < inorder.length; i++) {
        if (inorder[i] == rootValue) {
            k = i;
            break;
        }
    }

    root.left = buildTree(inorder, inStart, k - 1, postorder, postStart,
            postStart + k - (inStart + 1));
    // Becuase k is not the length, it it need to -(inStart+1) to get the length
    root.right = buildTree(inorder, k + 1, inEnd, postorder, postStart + k- inStart, postEnd - 1);
    // postStart+k-inStart = postStart+k-(inStart+1) +1

    return root;
}

05用两个栈实现队列

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

解法:push是正常的入栈。

           pop的话是stack1不为空且当stack2为空的时候就stack1中的数PO出来就push进stack2.但是如果stack2不为空,stack1中数不能转移到stack2中,先让stack2中的先全部出栈先。

import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
 public void push(int node) {
	    	
	    		stack1.push(node);
	    		
	    	
	        
	    }
	    
	     public int pop() {
	    	if(stack1.empty()&&stack2.empty()){
	    		throw  new RuntimeException("quequ is empty");
	    	}
	    	if(stack2.empty()){
	    	  while(!stack1.isEmpty()){
    			stack2.push(stack1.pop());
	    		}
	    	}
	   return stack2.pop();
           
	    }

}

06旋转数组的最小数字

题目描述

把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。

解法:直接利用二分法,查找数组中的最小的那个数

import java.util.ArrayList;
public class Solution {
    public int minNumberInRotateArray(int [] array) {
		int low = 0 ; int high = array.length - 1;   
        while(low < high){
            int mid = low + (high - low) / 2;        
            if(array[mid] > array[high]){
                low = mid + 1;
            }else if(array[mid] == array[high]){//为了解决11101这种类似情况
                high = high - 1;
            }else{
                high = mid;//考虑到只剩下两个元素的情况
            }   
        }
        return array[low];
    }
}

07斐波那契数

题目描述

大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。

n<=39

解法:在数学上,斐波纳契数列以如下被以递归的方法定义:F0=0,F1=1,Fn=F(n-1)+F(n-2)(n>=2,n∈N*)

           利用递归

代码:

public class Solution {
    public int Fibonacci(int n) {
		if(n==0){
			return 0;
		}
		if(n==1){
			return 1;
		}
		return Fibonacci(n-1)+Fibonacci(n-2);

    }
}

解法2:因为递归,如果是n的数很大的时候,就容易溢出,所以采取循环

public class Solution {
    public int Fibonacci(int n) {
        int a=1,b=1,c=0;
        if(n<0){
            return 0;
        }else if(n==1||n==2){
            return 1;
        }else{
            for (int i=3;i<=n;i++){
                c=a+b;
                b=a;
                a=c;
            }
            return c;
        }
    }
}

08跳台阶

题目描述

一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。

解法:跳台阶可以这样子想:跳第1级台阶有一种跳法,挑第二级台阶有2种跳法(可以一下子跳2级,可以跳两次1级的),那第三级台阶的话,可以有前面(跳第1级台阶的跳法+挑第二级台阶的跳法=3)一次类推f(n)=f(n-1)+f(n-2)

代码:

public class Solution {
   
        public int JumpFloor(int target) {
        if (target <= 0) {
            return 0;
        }
        if (target == 1) {
            return 1;
        }
        if (target == 2) {
            return 2;
        }
        int first = 1, second = 2, third = 0;
        for (int i = 3; i <= target; i++) {
            third = first + second;
            first = second;
            second = third;
        }
        return third;

    }
}

09变态跳台阶

题目描述

一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

解法:和前面跳台阶相似,只是现在的f(n)=f(n-1)+f(n-2)+....+f(1) 又因为f(n-1)=f(n-2)+...+f(1),所以f(n)=f(n-1)*2

代码:

public class Solution {
    public int JumpFloorII(int target) {
       if (target <= 0) {
            return -1;
        } else if (target == 1) {
            return 1;
        } else {
            return 2 * JumpFloorII(target - 1);
        }
    }
}
public class Solution {
    public int JumpFloorII(int target) {
        if(target == 0) {
            return 0;
        }
         
        int[] dp = new int[target + 1];
        dp[0] = 1;
        dp[1] = 1;
         
        for(int i = 2;i <= target;i++) {
            dp[i] = 0;
            for(int j = 0;j < i;j++) {
                dp[i] += dp[j];
            }
        }
         
        return dp[target];
    }
}

10.矩形覆盖

题目描述

我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?

解法:和之前的跳台阶问题相似

public class Solution {
    public int RectCover(int target) {
       if(target==1){
			return 1;
		}
        else if(target <=0){
            return 0;
        }
		else if(target==2){
			return 2;
		}
        else{
		return RectCover(target-1)+RectCover(target-2);
        }

    }
}

11.二进制中1的个数

题目描述

输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

解法:将数字转换成二进制的数组,再遍历数组得到1的数字。

public class Solution {
    public int NumberOf1(int n) {
        int t=0;
            char[]ch=Integer.toBinaryString(n).toCharArray();
            for(int i=0;i<ch.length;i++){
                if(ch[i]=='1'){
                    t++;
                }
            }
            return t;
	
    }
}
链接:https://www.nowcoder.com/questionTerminal/8ee967e43c2c4ec193b040ea7fbb10b8
来源:牛客网

/**
 * 思路:将n与n-1想与会把n的最右边的1去掉,比如
 * 1100&1011 = 1000
 * 再让count++即可计算出有多少个1
 * @author skyace
 *
 */
public class CountOne {
     public static int NumberOf1(int n) {
            int count = 0;
            while(n!=0){
                count++;
                n = n&(n-1);
            }
             
            return count;
        }
}

12.数值的整数次方

题目描述

给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。

解法1:

链接:https://www.nowcoder.com/questionTerminal/1a834e5e3e1a4b7ba251417554e07c00
来源:牛客网

传统公式求解时间复杂度O(n)
public class Solution {
    public double Power(double base, int exponent) {
        double  result=1;
        for(int i=0;i<Math.abs(exponent);i++){
            result*=base;
        }
        if(exponent<0){
            result=1/result;
        }
        return result;            
  }
}

 

解法2:

链接:https://www.nowcoder.com/questionTerminal/1a834e5e3e1a4b7ba251417554e07c00
来源:牛客网
快速幂算法

public double Power(double base, int exponent) {
        if (exponent == 0) {
            return 1.0;
        }
        if (base - 0.0 == 0.00001 || base - 0.0 == -0.00001)  {
            if (exponent < 0) {
                throw new RuntimeException("除0异常"); 
            }else{
                return 0.0;
            }
        }
        int e = exponent > 0 ? exponent: -exponent;
        double res = 1;
        while (e != 0) {
            res = (e & 1) != 0 ? res * base : res;
            base *= base;
            e = e >> 1;
        }
        return exponent > 0 ? res : 1/res;
  }

13调整数组顺序使奇数位于偶数前面

题目描述

输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。

解法:利用冒泡排序的想法,前偶后奇就交换。

public class Solution {
    public void reOrderArray(int [] array) {
        for(int i= 0;i<array.length-1;i++){
            for(int j=0;j<array.length-1-i;j++){
                if(array[j]%2==0&&array[j+1]%2==1){
                    int t = array[j];
                    array[j]=array[j+1];
                    array[j+1]=t;
                }
            }
        }
    }
}

14.链表中倒数第k个结点

题目描述

输入一个链表,输出该链表中倒数第k个结点。

解法:1.可以直接利用栈先进后出,先链表的结点全部进去,再利用for循环出来k个。

            2.可以先来链表1先有k-1个结点,然后一共有n个结点。

              链表1(从k个结点开始走)和链表2(从头结点开始走),当链表1走到链表末尾的时候,则刚好链表2走到的结点是倒数第k个结点。

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

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        if(null == head)
    {
        return null;
    }
    if(k <=0)
    {
        return null;
    }
 
    ListNode ptr = head;
    for(int i = 0; i < k - 1; i++)
    {
        ptr = ptr.next;
 
    }//for
 
    if(null == ptr)
    {
        return null;
    }//if
 
    ListNode pcur = head;
    while(null != ptr.next)
    {
        ptr = ptr.next;
        pcur = pcur.next;
    }//while
 
    return pcur;

    }
}

15.反转链表

题目描述

输入一个链表,反转链表后,输出新链表的表头。

解法:解法1:非递归,新建三个结点,走一步,反转一步

/*
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;
        }
        if(head.next==null){
            return head;
        }
        ListNode pre=head;
        ListNode mid=head.next;
        ListNode hehide=mid.next;
        while(hehide!=null){
            mid.next=pre;
            pre=mid;
            mid=hehide;
            hehide=hehide.next;
        }
        mid.next=pre;
        pre=mid;
       // mid=hehide;
        head.next=null;
        return pre;
    }
}

16.合并两个排序的链表

题目描述

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

解法:先从两个链表的头结点计较,哪一小就先插进去链表3,然后小的那个链表往下走。当其中哪一个链表走到尾端了,就把另一个链表剩下的结点放进链表3中。

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

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {




 if(list1==null){
		return list2;
	}
	if(list2==null){
		return list1;
	}
	ListNode head=new ListNode(-1);
	ListNode mergeHead=head;
	
	while(list1!=null&&list2!=null){
	if(list1.val<=list2.val){
		
			mergeHead.next=list1;
			list1=list1.next;
			
			
		}
	else{
		mergeHead.next=list2;
		list2=list2.next;
		
		
	 }
        mergeHead = mergeHead.next;
	} 
       if (list1 != null) mergeHead.next = list1;
        if (list2 != null) mergeHead.next = list2;
	return head.next;
    
    }
}

17.树的子结构

题目描述

输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)

解法:https://www.nowcoder.com/profile/562667/codeBookDetail?submissionId=1523155

/*思路:参考剑指offer

1、首先设置标志位result = false,因为一旦匹配成功result就设为true,

剩下的代码不会执行,如果匹配不成功,默认返回false

2、递归思想,如果根节点相同则递归调用DoesTree1HaveTree2(),

如果根节点不相同,则判断tree1的左子树和tree2是否相同,

再判断右子树和tree2是否相同

3、注意null的条件,HasSubTree中,如果两棵树都不为空才进行判断,

DoesTree1HasTree2中,如果Tree2为空,则说明第二棵树遍历完了,即匹配成功,

tree1为空有两种情况(1)如果tree1为空&&tree2不为空说明不匹配,

(2)如果tree1为空,tree2为空,说明匹配。

 

*/

public class Solution {
    public boolean HasSubtree(TreeNode root1,TreeNode root2) {
        boolean result = false;
            if(root1 != null && root2 != null){
                if(root1.val == root2.val){
                    result = DoesTree1HaveTree2(root1,root2);
                }
                if(!result){result = HasSubtree(root1.left, root2);}
                if(!result){result = HasSubtree(root1.right, root2);}
            }
            return result;
    }
    public boolean DoesTree1HaveTree2(TreeNode root1,TreeNode root2){
            if(root1 == null && root2 != null) return false;
            if(root2 == null) return true;
            if(root1.val != root2.val) return false;
            return DoesTree1HaveTree2(root1.left, root2.left) && DoesTree1HaveTree2(root1.right, root2.right);
        }
}

18.二叉树的镜像

题目描述

操作给定的二叉树,将其变换为源二叉树的镜像。

输入描述:

二叉树的镜像定义:源二叉树 
    	    8
    	   /  \
    	  6   10
    	 / \  / \
    	5  7 9 11
    	镜像二叉树
    	    8
    	   /  \
    	  10   6
    	 / \  / \
    	11 9 7  5

解法:

**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public void Mirror(TreeNode root) {
        if(root == null)
            return;
        if(root.left == null && root.right == null)
            return;
         
        TreeNode pTemp = root.left;
        root.left = root.right;
        root.right = pTemp;
         
        if(root.left != null)
            Mirror(root.left);
        if(root.right != null)
            Mirror(root.right);
    }
}

20.顺时针打印矩阵

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
	    	ArrayList<Integer> result=new ArrayList<Integer>();
	    	if(matrix==null||matrix.length==0){
	    		return result;
	    	}
	    	printMatrixClockWisely(matrix, 0, 0, matrix.length - 1, matrix[0].length - 1, result);
	    	
	    	return result;
	       
	    }
	    public void printMatrixClockWisely(int[][] matrix, int startRow, int startCol, int endRow, int endCol, ArrayList<Integer> result) {
	        if(startRow<endRow && startCol<endCol) {
	            for(int j=startCol; j<=endCol; j++) { result.add(matrix[startRow][j]) ; }   //Right
	            for(int i=startRow+1; i<=endRow-1; i++) { result.add(matrix[i][endCol]) ; }     //Down
	            for(int j=endCol; j>=startCol; j--) { result.add(matrix[endRow][j]) ; }     //Left
	            for(int i=endRow-1; i>=startRow+1; i--) { result.add(matrix[i][startCol]) ; }   //Up
	            printMatrixClockWisely(matrix, startRow + 1, startCol + 1, endRow - 1, endCol - 1, result) ;
	        }else if(startRow==endRow && startCol<endCol) {
	            for(int j=startCol; j<=endCol; j++) { result.add(matrix[startRow][j]) ; }
	        }else if(startRow<endRow && startCol==endCol) {
	            for(int i=startRow; i<=endRow; i++) { result.add(matrix[i][endCol]) ; }
	        }else if(startRow==endRow && startCol==endCol) {
	            result.add(matrix[startRow][startCol]) ;
	        }else {
	            return ;
	        }
	    }
	
}

21包含min函数的栈

题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

解法:

import java.util.Stack;
import java.util.Iterator;
public class Solution {

    
   
    Stack<Integer> stack = new Stack<Integer>();
	    public void push(int node) {
	        stack.push(node);
	    }
	 
	    public void pop() {
	        stack.pop();
	    }
	 
	    public int top() {
	        return stack.peek();
	    }
	 
	    public int min() {
	        int min = stack.peek();
	   
	        int tmp = 0;
	        Iterator<Integer> iterator = stack.iterator();
	        while (iterator.hasNext()){
	            tmp = iterator.next();
	            if (min>tmp){
	                min = tmp;
	            }
	        }
	        return min;
	    }
}

 

import java.util.Stack;
import java.util.Arrays;
public class Solution {
/*借用辅助栈存储min的大小,自定义了栈结构
*/
    private int size;
    private int min = Integer.MAX_VALUE;
    private Stack<Integer> minStack = new Stack<Integer>();
    private Integer[] elements = new Integer[10];
    public void push(int node) {
        ensureCapacity(size+1);
        elements[size++] = node;
        if(node <= min){
            minStack.push(node);
            min = minStack.peek();
        }else{
            minStack.push(min);
        }
    //    System.out.println(min+"");
    }
 
    private void ensureCapacity(int size) {
        // TODO Auto-generated method stub
        int len = elements.length;
        if(size > len){
            int newLen = (len*3)/2+1; //每次扩容方式
            elements = Arrays.copyOf(elements, newLen);
        }
    }
    public void pop() {
        Integer top = top();
        if(top != null){
            elements[size-1] = (Integer) null;
        }
        size--;
        minStack.pop();    
        min = minStack.peek();
    //    System.out.println(min+"");
    }
 
    public int top() {
        if(!empty()){
            if(size-1>=0)
                return elements[size-1];
        }
        return (Integer) null;
    }
    public boolean empty(){
        return size == 0;
    }
 
    public int min() {
        return min;
    }
}

22.栈的压入、弹出序列

题目描述

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

import java.util.ArrayList;
import java.util.Stack;
public class Solution {
    Stack<Integer> stack = new Stack<Integer>();
	    int popIndex = 0;
	    public boolean IsPopOrder(int [] pushA,int [] popA) {
	        for(int i=0;i<pushA.length;i++){
	            stack.push(pushA[i]);
	            while(!stack.empty() &&stack.peek() == popA[popIndex]){
	                
	                stack.pop();
	               
	                popIndex++;
	            }
	        }
	    
	    return stack.empty();
        }
}

23从上往下打印二叉树(相当于二叉树的层次遍历)

题目描述

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

解答:相当于二叉树的层次遍历,利用队列

import java.util.ArrayList;
 import java.util.Queue;

import java.util.LinkedList;

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
      ArrayList<Integer> list=new ArrayList<>();
      if(root == null){
            return list;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        int  count = 0, nextCount = 1;
        while(queue.size()!=0){
            TreeNode top = queue.poll();
            count++;
            list.add(top.val);
            if(top.left != null){
                queue.add(top.left);
            }
            if(top.right != null){
                queue.add(top.right);
            }
            //表示一层遍历结束
            if(count == nextCount){
                nextCount = queue.size();
                count = 0;
            }
        }
        return list;
        
    }
}

24.二叉搜索树的后序遍历序列

题目描述

输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。

解答:因为二叉搜索树是有序的,二叉搜索树的后序遍历序列应该满足前面一段是小于最后一个结点的,剩下的一段是大于最后结点的,以此类推,利用递归。

public class Solution {
    public boolean VerifySquenceOfBST(int [] sequence) {
        if(sequence.length == 0) return false;
        return IsTreeBST(sequence, 0, sequence.length-1);
    }
    public boolean IsTreeBST(int [] sequence,int start,int end ){
        if(end <= start) return true;
        int i = start;
        for (; i < end; i++) {
            if(sequence[i] > sequence[end]) break;
        }//判断左子树小于根节点
        for (int j = i; j < end; j++) {
            if(sequence[j] < sequence[end]) return false;
        }//判断右子树大于根节点
        return IsTreeBST(sequence, start, i-1) && IsTreeBST(sequence, i, end-1);//递归左右子树都是合法的后序序列
    }
}

25.二叉树中和为某一值的路径

题目描述

输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)

解法:先序遍历+回溯法(到了叶节点往回退)

import java.util.ArrayList;
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    private ArrayList<ArrayList<Integer>> listAll = new ArrayList<ArrayList<Integer>>();
    private ArrayList<Integer> list = new ArrayList<Integer>();
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
        if(root == null) return listAll;
        list.add(root.val);
        target -= root.val;//路径中一定会有根节点的,所以要减去根节点的值
        if(target == 0 && root.left == null && root.right == null)
            listAll.add(new ArrayList<Integer>(list));
        FindPath(root.left, target);//
        FindPath(root.right, target);
        list.remove(list.size()-1);//递归到叶子节点如果还没有找到路径,就要回退到父节点继续寻找,依次类推
        return listAll;
    }
}

26.复杂链表的复制

题目描述

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

解法:先复制复杂链表中的值和指向下一个结点的指针,然后再复制特殊指针,原本的复杂链表和复制的链表现在在同一个链表里面,现在一分为2就可以得到复制后链表的head了。

public class Solution {
    public RandomListNode Clone(RandomListNode pHead) {
        if(pHead == null) {
            return null;
        }
         
        RandomListNode currentNode = pHead;
        //1、复制每个结点,如复制结点A得到A1,将结点A1插到结点A后面;
        while(currentNode != null){
            RandomListNode cloneNode = new RandomListNode(currentNode.label);
            RandomListNode nextNode = currentNode.next;
            currentNode.next = cloneNode;
            cloneNode.next = nextNode;
            currentNode = nextNode;
        }
         
        currentNode = pHead;
        //2、重新遍历链表,复制老结点的随机指针给新结点,如A1.random = A.random.next;
        while(currentNode != null) {
            currentNode.next.random = currentNode.random==null?null:currentNode.random.next;
            currentNode = currentNode.next.next;
        }
         
        //3、拆分链表,将链表拆分为原链表和复制后的链表
        currentNode = pHead;
        RandomListNode pCloneHead = pHead.next;
        while(currentNode != null) {
            RandomListNode cloneNode = currentNode.next;
            currentNode.next = cloneNode.next;
            cloneNode.next = cloneNode.next==null?null:cloneNode.next.next;
            currentNode = currentNode.next;
        }
         
        return pCloneHead;
    }
}

(图来自牛客网讨论区)

27.二叉搜索树与双向链表

题目描述

输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

解答:中序遍历

          先递归到左子树的最后一个左结点,设它为双向链表的头结点,利用realhead保存着,再慢慢的返回去,利用 

           head.right = pRootOfTree;
            pRootOfTree.left = head;

这两句达到双向链表的目的
            head = pRootOfTree;//走向下一个链表的下一个结点。

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    
          TreeNode head = null;
    TreeNode realHead = null;
    public TreeNode Convert(TreeNode pRootOfTree) {
        ConvertSub(pRootOfTree);
        return realHead;
    }
     
    private void ConvertSub(TreeNode pRootOfTree) {
        if(pRootOfTree==null) return;
        ConvertSub(pRootOfTree.left);
        if (head == null) {
            head = pRootOfTree;
            realHead = pRootOfTree;
        } else {
            head.right = pRootOfTree;
            pRootOfTree.left = head;
            head = pRootOfTree;
        }
        ConvertSub(pRootOfTree.right);
    }
    
}

28.字符串的排列

题目描述

输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。

输入描述:

输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。

import java.util.ArrayList;
import java.util.Collections;
public class Solution {
     public ArrayList<String> Permutation(String str) {
    	ArrayList<String> res = new ArrayList<>();
        if (str != null && str.length() > 0) {
            PermutationHelper(str.toCharArray(), 0, res);
            Collections.sort(res);//为了最终打印的字符串是按着字典排序的
        }
        return res;
    }
 
    public void PermutationHelper(char[] cs, int i, ArrayList<String> list) {
        if (i == cs.length - 1) {//递归的出口
            String val = String.valueOf(cs);
            if (!list.contains(val))//考虑数组中有重复元素出现的情况
                list.add(val);
        } else {
            for (int j = i; j < cs.length; j++) {
                swap(cs, i, j);
                PermutationHelper(cs, i+1, list);
                swap(cs, i, j);//第二个swap保证程序发生交换后,恢复到交换之前的状态。举个例子:对于上图的左子树,当程序将ACB加入到list中,此时数组的状态就是ACB,因为递归的原因,程
                //序会退栈回到根节点。如果没有第二个swap的话,此时的根节点是ACB,而不是ABC,
            }
        }
    }
 
    public void swap(char[] cs, int i, int j) {
        char temp = cs[i];
        cs[i] = cs[j];
        cs[j] = temp;
    }
}

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值