331. Verify Preorder Serialization of a Binary Tree

来源:互联网 发布:淘宝旺铺2016年多少钱 编辑:程序博客网 时间:2024/05/21 13:59
public static boolean isValidSerialization(String preorder) {        if(preorder == null || preorder.length() == 0) {            return false;        }else {            Stack<String> stack = new Stack<String>();            String[] str = preorder.split(",");            if(str.length == 2) {                return false;            }            int i = 0;            boolean is = true;            for(i = 0; i < str.length; i++) {                if(str[i].equals("#")) {                    String pc1 = "#";                    String pc2 = "";                    if(!stack.isEmpty()) {                        pc2 = stack.peek();                    }else {                        if(i == str.length) {                            stack.push("#");                            break;                        }else {                            is =false;                            break;                        }                    }                    while(pc1.equals("#") && pc1 == pc2) {                        stack.pop();                        if(stack.isEmpty()) {                            is = false;                            break;                        }                        String cc = stack.peek();                        if(cc.equals("#")) {                            is = false;                            break;                        }else {                            stack.pop();                            pc1 = "#";                            if(!stack.isEmpty()) {                                pc2 = stack.peek();                            }else {                                pc2 = "";                                break;                            }                        }                    }                    if(is) {                        stack.push(pc1);                    }else {                        break;                    }                }else {                    stack.push(str[i]);                }            }            if(!is) {                return false;            }else {                if(stack.isEmpty()) {                    return false;                }else{                    String pc = stack.peek();                    stack.pop();                    if(pc.equals("#") && stack.isEmpty()) {                        return true;                    }else {                        return false;                    }                }            }        }    }
0 0
原创粉丝点击