首页 > 新浪9.13笔试,看到挺多人代码还有问题,留一下AC代码吧
头像
追风少年风中追风
编辑于 2020-09-13 19:02
+ 关注

新浪9.13笔试,看到挺多人代码还有问题,留一下AC代码吧

看到挺多人代码还有问题,留一下AC代码吧

第一题 就是建树然后旋转,不难但是代码挺多的

package com.xinlang;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main01 {
    private static TreeNode newRoot;
    private static boolean notFind = true;
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String[] nodes = in.nextLine().split(",");
        TreeNode root = new TreeNode(Integer.parseInt(nodes[0]));
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int i =1;
        while (i<nodes.length)
        {
            TreeNode node = queue.poll();
            TreeNode left = new TreeNode(Integer.parseInt(nodes[i++]));
            node.left = left;
            queue.add(left);
            TreeNode right = new TreeNode(Integer.parseInt(nodes[i++]));
            node.right = right;
            queue.add(right);
        }
        postOrder(root);
        printTree(newRoot);
    }
    private static void postOrder(TreeNode root) {
        if (root.left==null&&notFind)
        {
            notFind=false;
            newRoot=root;
        }
        if (root.left==null)
            return;
        postOrder(root.left);
        TreeNode left = root.left;
        TreeNode right = root.right;
        root.left=null;
        root.right=null;
        left.left=right;
        left.right=root;
    }

    private static void printTree(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty())
        {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                sb.append(node.val+",");
                if (node.left!=null)
                    queue.add(node.left);
                if (node.right!=null)
                    queue.add(node.right);
            }
        }
        sb.deleteCharAt(sb.length()-1);
        System.out.println(sb.toString());
    }
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode(int x) {
            val = x;
        }
    }

}

第二题 排序就行了

package com.xinlang;

import java.util.Arrays;
import java.util.Scanner;

public class Mian02 {
    public static void main(String[] args) {
        System.out.println(go());
    }

    private static boolean go() {
        Scanner in = new Scanner(System.in);
        char[] chars = in.nextLine().toCharArray();
        if (chars.length==1)
            return true;
        Arrays.sort(chars);
        for (int i = 1; i < chars.length; i++) {
            if (chars[i]==chars[i-1])
                return false;
        }
        return true;
    }
}

全部评论

(4) 回帖
加载中...
话题 回帖

推荐话题

相关热帖

历年真题 真题热练榜 24小时
技术(软件)/信息技术类
查看全部

近期精华帖

热门推荐