Offer brush prove safety issues (b) and ideas

Pressed into the stack, pop-up sequence

Two input sequence of integers, the first sequence representing a pressed stack order, determines whether it is possible for the second sequence the order of the pop-up stack. All figures are not pushed onto the stack is assumed equal. Such as a sequence of a sequence of 1,2,3,4,5 is pressed into the stack, the push sequence is 4,5,3,2,1 sequence corresponding to a sequence of pop, but 4,3,5,1,2 it is impossible to push pop-up sequence of the sequence. (Note: the length of the two sequences are equal)

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

        }
        return stack.isEmpty();
        
    }
}

Direct simulation of the subject described processes can be pushed and popped,
for example as a stack 1234, to 4, the stack is detected and the sequence identical to the first, to pop, the stack is the next 5, then of the stack 123, the stack 5, to be the same as the stack is detected, pop, proceed sequentially, and finally if the stack is empty, it is described a stack pop sequence

Print binary tree from the top down

Downward from the print out of each node of the binary tree, with the layer node from left to right printing.

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 {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
       
        ArrayList<Integer> list = new ArrayList<Integer>();
        ArrayList<TreeNode> queue = new ArrayList<TreeNode>();
         if(root==null) return list;
        queue.add(root);
        while(queue.size()!=0)
        {
            TreeNode tmp = queue.remove(0);
            if(tmp.left!=null)
            {
                queue.add(tmp.left);
            }
            if(tmp.right!=null)
            {
                queue.add(tmp.right);
            }
            list.add(tmp.val);
        }
        return list;
    }

}

A queue implementation, were added node, the left child node and the right child node to the queue,
order taking in a first queue, the node about its queued, then the value is added to the list, until the queue is taken air

Subsequent binary search tree traversal sequence

Enter an integer array, the array is not the result of the determination after traversing a binary search tree. If the output Yes, otherwise the output No. Suppose the input array of any two numbers are different from each other.

public class Solution {
    public boolean VerifySquenceOfBST(int [] sequence) {
        int length = sequence.length;
        if(length==1)return true;
        if(length==0)return false;
        return isTree(sequence,0,length-1);
        
        
    }
    public static boolean isTree(int[] subarr, int begin,int end)
    {
        int i = end-1;
        if(begin>end)return true;
        
        //从数组的最后一个元素向前遍历,最后一个元素必定是根节点,往前找直到找到比它小的
        while( i>begin && subarr[i] > subarr[end] )
        {
            i--;
        }
        //找到比根节点小的元素位置,以这个元素为基准,左边是左子树部分,右边是右子树部分
        //右边的右子树部分已经验证都比根节点大,那么开始验证左边是不是都比根节点小
        int leftend = i;
        //如果全部元素都大于最后一个根结点,就没有左边的元素,也是成立的
        if(leftend==0)return true;
        while(i>=begin)
        {
            if(subarr[i]>subarr[end])return false;
            i--;
        }
        //左边的都满足比根节点小,进行分割递归调用
        return isTree(subarr,begin,leftend) && isTree(subarr,leftend+1,end-1);
        
    }
}

It is a binary tree search as shown below and its postorder traversal

Here Insert Picture DescriptionHere Insert Picture Description
To determine whether a sequence is not a binary search tree postorder, we must first clear:

  • The last element of the sequence must be the root node
  • The left half of the root node than the root of all small, large root than the right half
  • Each intermediate node also have this property

So, to find the last element A sequence of forward traversal, find the first elements of A smaller than B, illustrate this element is left subtree of the node A, then they would have to meet and then move through all the elements of value must be a smaller ratio, otherwise exit the traverse returns false (to ensure that the right half case has relatively large a, since B is less than a, the first)
If this layer is determined completed, to put the elements of the array B into intermediate two halves, each half then determined according to the above rules, is divided into individual elements until
Here Insert Picture Description

For a binary tree and path value

输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的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>> List = new ArrayList<ArrayList<Integer>>();
    //子list
    private ArrayList<Integer> subList = new ArrayList<Integer>();
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
       if(root == null)return List;
        
        subList.add(root.val);
        //每加入一个结点的值,就把目标和数值减去这个值
        target -= root.val;
        //当前结点若为叶子结点,且subList中所有元素的和等于target
        //就把这个subList加入List
        if(target == 0 &&root.left==null&&root.right== null)
        {
            //必须要 new 一个新的list,否则后面移除元素时会造成影响
            List.add(new ArrayList<Integer>(subList));
        }
        FindPath(root.left,target);
        FindPath(root.right,target);
            //递归到底后,需要退回上一层结点,故加入的结点要去掉一个
        subList.remove(subList.size()-1);
        return List;
        
        
        
        }
    
    
}

复杂链表的复制

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

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

    RandomListNode(int label) {
        this.label = label;
    }
}
*/
import java.util.HashMap;
public class Solution {
    public RandomListNode Clone(RandomListNode pHead)
    {
        if(pHead==null)return pHead;
        //整一个HashMap,key是原来的Node结点,Value是复制后的Node结点
        HashMap<RandomListNode,RandomListNode> map = new HashMap<RandomListNode,RandomListNode>();
        RandomListNode cur = pHead ; 
        while(cur !=null)
        {
            map.put(cur,new RandomListNode(cur.label));
            cur = cur.next;
        }
        
        RandomListNode res = map.get(pHead);
        cur = pHead;
        while(cur!=null)
        {
            map.get(cur).next = map.get(cur.next);
            map.get(cur).random = map.get(cur.random);
            cur = cur.next;
        }
        return res;
    }
}

一个HashMap,key是原来的链表节点,value是新的链表节点,刚开始put进去时,value只有复制的一份节点值,没有next和random,通过get取到相应节点的复制节点,然后把原节点的next和random对象赋给复制节点的next和random引用
Here Insert Picture Description
进行复制信息的操作解释:
Here Insert Picture Description

二叉搜索树与双向链表

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

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

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

    }

}
*/
public class Solution {
    public TreeNode Convert(TreeNode root) {
    	//如果节点为null,直接返回null
        if(root == null) return null;
        //如果节点为叶子节点,返回该节点
        if(root.left==null&&root.right==null)
            return root;
        //左子树递归地构造成双向链表
        TreeNode left = Convert(root.left);
        TreeNode p = left;
        //遍历到双向链表的最右边
        while(p!=null&&p.right!=null)
        {
            p=p.right;
        }
        if(left!=null)
        {
            p.right =root;
            root.left = p;
        }
        //右边也一样
        TreeNode right = Convert(root.right);
        if(right!=null)
        {
            right.left=root;
            root.right =right;
        }
        if(left!=null)return left;
        return root;
    }
    

}

Here Insert Picture Description
如图一棵二叉搜索树,要转变为
Here Insert Picture Description

字符串的排列

输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。

import java.util.*;
public class Solution {
    public ArrayList<String> Permutation(String str) {
        ArrayList<String> list = new ArrayList<String>();
       char[] charArr = str.toCharArray();
       if(str!=null){
           fun(charArr,list,0);
           Collections.sort(list);
       }
        return list;
       
       
    }
    
    public static void fun(char[] charArr,ArrayList<String> list,int i)
    {
        if(i==charArr.length-1)
        {
            String str = String.valueOf(charArr);
            if(!list.contains(str))
            {
                list.add(str);
            }
        }
        for(int j = i;j<charArr.length;j++)
        {
            swap(charArr,j,i);
            fun(charArr,list,i+1);
            swap(charArr,j,i);
        }
    }
    
    public static void swap(char[] charArr,int i,int j)
    {
        if(i!=j)
        {
            char tmp = charArr[i];
            charArr[i] = charArr[j];
            charArr[j] = tmp;
        }
    }
}

全排列,用递归做
ABC ,固定A i=0,j=0 swap

  • BC,固定B i=1,j=1 swap
    • C,添加ABC i=2,j=2 swap
  • CB,固定C i=1,j=2 swap
    • B,添加ACB i=1,j=2 swap

BAC,固定B i=0,j=1 swap

  • AC,固定A i=1,j=1 swap
    • C,添加BAC i=2,j=2 swap
  • CA,固定C i=1,j=2 swap
    • A, was added BCA i = 1, j = 2 swap

CBA, fixed C i = 0, j = 2 swap

  • BA, fixing B i = 1, j = 1 swap
    • A, was added CBA i = 2, j = 2 swap
  • AB, fixing A i = 1, j = 2 swap
    • B, add CAB i = 1, j = 2 swap

Full array write himself dizzy. . .
Ij found the same, swap does not change the original value, after different ij, swap only on the basis of changes in the original

Published 16 original articles · won praise 2 · Views 1823

Guess you like

Origin blog.csdn.net/weixin_43925277/article/details/104569481