Sword finger offer_ Programming questions_ java version (21-27)

Keywords: Java less

Article catalog

Push and pop sequence of stack

Title Description
Enter two integer sequences. The first sequence represents the push order of the stack. Please judge whether the second sequence is the pop-up order of the stack. Assume that all the numbers pushed into the stack are not equal. For example, sequence 1,2,3,4,5 is the pressing sequence of a stack, sequence 4,5,3,2,1 is a pop-up sequence corresponding to the pressing sequence, but 4,3,5,1,2 cannot be the pop-up sequence of the pressing sequence. (Note: the two sequences are the same length)

import java.util.ArrayList;
import java.util.Stack;
/**
Idea: create A new stack, and press array A into the stack. When the top element of the stack is equal to array B,
When the loop ends, judge whether the stack is empty. If it is empty, return true
*/
public class Solution {
    public boolean IsPopOrder(int [] pushA,int [] popA) {
      if(pushA.length==0||popA.length==0 || pushA.length!=popA.length){
          return false;
      }else{
          Stack<Integer> stack=new Stack<Integer>();
          int j=0;
          for(int i=0;i<pushA.length;i++){
              stack.push(pushA[i]);
               while (!stack.isEmpty() && stack.peek() == popA[j]){
                   stack.pop();
                   j++;
               }
          }
          return stack.isEmpty();
      }
    }
}

Print binary tree from top to bottom

Title Description
Each node of the binary tree is printed from top to bottom, and the nodes of the same layer are printed from left to right.

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
/**
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> arrayList = new ArrayList<Integer>();
        if (root==null){
            return arrayList;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        while (!queue.isEmpty()){
            TreeNode node= queue.poll();
            arrayList.add(node.val);
            if (node.left!=null){
                queue.add(node.left);
            }
            if (node.right!=null){
                queue.add(node.right);
            }
        }
        return arrayList;
    }
}

Post order traversal sequence of binary search tree

Title Description
Input an integer array to determine whether the array is the result of the subsequent traversal of a binary search tree. If Yes, output Yes; otherwise, output No. Suppose that any two numbers of the input array are different from each other.

/**
Only the left subtree interval and the right subtree interval need to be determined continuously, and the judgment:
All node values of left subtree interval < root node value < all node values of right subtree interval
*/

public class Solution {
 public boolean helpVerify(int [] sequence, int start, int root){
        if(start >= root)return true;
        int key = sequence[root];
        int i;
        //Find the dividing point of left and right subnumbers
        for(i=start; i < root; i++)
            if(sequence[i] > key)
                break;
        //Judge whether there is a value less than root in the right subtree, and return false if there is one
        for(int j = i; j < root; j++)
            if(sequence[j] < key)
                return false;
        return helpVerify(sequence, start, i-1) && helpVerify(sequence, i, root-1);
    }
    public boolean VerifySquenceOfBST(int [] sequence) {
        if(sequence == null || sequence.length == 0)return false;
        return  helpVerify(sequence, 0, sequence.length-1);

    }
}

Path with a certain value in a binary tree

Title Description
Input the root node and an integer of a binary tree, and print out all paths whose sum of node values in the binary tree is the input integer. Path is defined as a path from the root node of the tree to the node that the leaf node passes through.

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>> result = new ArrayList<ArrayList<Integer>>();
    private ArrayList<Integer> list = new ArrayList<>();
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
        if(root == null)return result;
        list.add(root.val);
        target -= root.val;
        if(target == 0 && root.left == null && root.right == null)
            result.add(new ArrayList<Integer>(list));
//Because we use the same result reference in every recursion, we don't need to care about the result of left and right subtree recursion,
//Can be abbreviated to findpath( root.left , target);FindPath(root.right, target);
//But in order for you to see the truth of recursion, here I still show you the form of recursion.
        ArrayList<ArrayList<Integer>> result1 = FindPath(root.left, target);
        ArrayList<ArrayList<Integer>> result2 = FindPath(root.right, target);
        list.remove(list.size()-1);
        return result;
    }
}

Replication of complex linked list

Title Description
Enter a complex linked list (each node has a node value, and two pointers, one to the next node, and another special pointer random to a random node). Please make a deep copy of this linked list and return the copied head node. (Note: please do not return the node reference in the parameter in the output result, otherwise the problem determination program will directly return null)

/*
public class RandomListNode {
    int label;
    RandomListNode next = null;
    RandomListNode random = null;

    RandomListNode(int label) {
        this.label = label;
    }
}
*/
import java.util.ArrayList;
public class Solution {
   public RandomListNode Clone(RandomListNode pHead)
    {
        if (pHead == null) return null;
        RandomListNode head = new RandomListNode(pHead.label);
        RandomListNode ans = head;
        if (pHead.random != null) {
            head.random = new RandomListNode(pHead.random.label);
        }
        while (pHead.next != null) {
            pHead = pHead.next;
            head.next = new RandomListNode(pHead.label);
            if (pHead.random != null) {
                head.next.random = new RandomListNode(pHead.random.label);
            }
            head = head.next;
        }
        return ans;
    }
}

Binary search tree and double linked list

Title Description
Input a binary search tree, and transform the binary search tree into a sorted bidirectional linked list. It is required that no new node can be created, only the node pointer in the tree can be adjusted.

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

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

    }

}
*/
import java.util.ArrayList;
public class Solution {
public TreeNode Convert(TreeNode pRootOfTree) {
        if(pRootOfTree == null){
            return null;
        }
        ArrayList<TreeNode> list = new ArrayList<>();
        Convert(pRootOfTree, list);
        return Convert(list);

    }
    //Middle order traversal, saved in the list in the order of traversal
    public void Convert(TreeNode pRootOfTree, ArrayList<TreeNode> list){
        if(pRootOfTree.left != null){
            Convert(pRootOfTree.left, list);
        }

        list.add(pRootOfTree);

        if(pRootOfTree.right != null){
            Convert(pRootOfTree.right, list);
        }
    }
    //Traverse list, modify pointer
    public TreeNode Convert(ArrayList<TreeNode> list){
        for(int i = 0; i < list.size() - 1; i++){
            list.get(i).right = list.get(i + 1);
            list.get(i + 1).left = list.get(i);
        }
        return list.get(0);
    }
}

Arrangement of strings

Title Description
Enter a string and print all the permutations of the characters in the string in dictionary order. For example, the input string a B C will print out all the strings abc, a C B, BAC, B C A, cab and cba that can be arranged by the characters a, B and C.
Enter a description:
Enter a string that is no longer than 9 (there may be duplicate characters) and contains only uppercase and lowercase letters.

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
 
    public TreeNode(int val) {
        this.val = val;
 
    }
 
}
*/
import java.util.*;
public class Solution
{
   public ArrayList<String> Permutation(String str)
    {
        ArrayList<String> res=new ArrayList<String>();
        if(str.length()==0||str==null)return res;
        int n= str.length();
        helper(res,0,str.toCharArray());
        Collections.sort(res);
        return res;
         
    }
    public void helper( ArrayList<String> res,int index,char []s)
    {
        if(index==s.length-1)res.add(new String(s));
        for(int i=index;i<s.length;i++)
        {
            if(i==index||s[index]!=s[i])
            {
                swap(s,index,i);
                helper(res,index+1,s);
                swap(s,index,i);
            }
        }
         
    }
     
    public void swap(char[]t,int i,int j)
     {
        char c=t[i];
        t[i]=t[j];
        t[j]=c;
    }
}

Posted by Delaran on Thu, 04 Jun 2020 06:26:48 -0700