2019秋招 | 小米线上笔试——中序遍历打印二叉树(软件开发工程师-Java方向)

2019秋招 | 小米线上笔试——中序遍历打印二叉树(软件开发工程师-Java方向)_第1张图片
输入:1(2(3,4(,5)),6(7,)
输出:3245176

后续补菜鸡代码,不知道通过率,emmmm

    import java.util.Scanner;
    
    /**
     * @Date:2019年9月7日上午6:26:07
     */
    public class T {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Scanner sc = new Scanner(System.in);
    		String s = sc.nextLine();
    		
    		TreeNode root = new TreeNode(null, null, null, s.charAt(0));
    		//System.out.println("根:"+root.val+",串长:"+s.length());
    		TreeNode tmp = root;
    		char pre='(';
    		char c=' ';
    		for(int i=1;i<s.length();i++){
    			c = s.charAt(i);
    			//System.out.println("第"+i+"个字符"+c);
    			pre=s.charAt(i-1);	
    			if (pre == '(') {
    				//tmp.left = new TreeNode(tmp,null,null,' ');
    				if (c != ',') {//情况"(,"
    					//System.out.println("1.pre:"+pre+",c:"+c);
    					tmp.left = new TreeNode(tmp,null,null,c);
    					tmp=tmp.left;
    					//System.out.println("根"+tmp.val+"\n");
    					//midOrder(root);
    				}
    			}
    			else if(pre==','){//情况",)"
    				if(c!=')'){
    					//System.out.println("2.pre:"+pre+",c:"+c);
    					tmp.right=new TreeNode(tmp,null,null,c);
    					tmp=tmp.right;
    					//System.out.println("根"+tmp.val+"\n");
    					//midOrder(root);
    				}
    			}
    			else if (c==','||c==')'&&pre==')'||c==')'){
    				tmp = tmp.father;
    				//System.out.println("根"+tmp.val+"\n");
    				//midOrder(root);
    			}
    		}
    		midOrder(root);
    	}
    
    	private static void midOrder(TreeNode root) {
    		if (root == null)
    			return;
    		midOrder(root.left);
    		System.out.print(root.val);
    		midOrder(root.right);
    	}
    }
    
    //定义树叶结点
    class TreeNode {
    	TreeNode father;
    	TreeNode left; 
    	TreeNode right;
    	char val;
    
    	public TreeNode(TreeNode father, TreeNode left, TreeNode right, char val) {
    		this.father = father;
    		this.left = left;
    		this.right = right;
    		this.val = val;
    	}

    }
    
    //测试数据
    // 1(2(3,4(,5)),6(7,)
    //串长19,3245176
    //5(8(,9(6,7(,4))))
    //869745

你可能感兴趣的:(秋招那些事,笔试题,小米,二叉树,遍历)