0

再帰なしでスタックを使用してポストオーダーを取得する方法は? ジャバがおすすめ!ありがとう!

以下は私の答えですが、2つの隠されたテストケースに合格できませんでした...誰でも助けてくれますか? ありがとう!

import java.io.*;
import java.util.Scanner;
import java.util.Stack;
public class Solution {
public static void main(String args[] ) throws Exception {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    Scanner sc = new Scanner(System.in);
    String cur = "";
    Stack<Integer> stack = new Stack<Integer>();
    while(sc.hasNextLine()){
        cur = sc.nextLine();
        Integer curIn = Integer.valueOf(cur);
        if(stack.isEmpty() || stack.peek() > curIn){
            stack.push(curIn);
        }else{
            Integer root = null; 
            Integer max = stack.peek();
            while(!stack.isEmpty() && (stack.peek() < curIn || (root != null && stack.peek() < root))){
                if(root != null)
                    System.out.println(root);
                root = stack.pop();
                max = Math.max(root, max);
            }
            stack.push(root);
            stack.push(curIn);
        }
    }
    while(!stack.isEmpty()){
        System.out.println(stack.pop());
    }
}
}
4

0 に答える 0