BST给出预订,如何使用堆栈获得postorder而不递归? 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());
}
}
}