BST给定预购,如何在不递归的情况下使用堆栈获取后购?首选Java!谢谢!
以下是我的答案,但未能通过 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());
}
}
}