Simple java stack solution


  • 0
    I
    public class Solution {
        public boolean isValidSerialization(String preorder) {
            
            String[] data = preorder.split(",");
            Stack<Boolean> st = new Stack<Boolean>();
            for(int i = 0; i < data.length; i++) {
                if(data[i].equals("#")) {
                    if(st.isEmpty()) {
                        return i + 1 == data.length;
                    }
                    
                    if(st.peek()) {
                        while(!st.isEmpty() && st.peek()) {
                            st.pop();
                        }
                     
                        if(st.isEmpty()) {
                            return i + 1 == data.length;
                        }
                        
                        if(!st.isEmpty()) {
                            st.pop();
                            st.push(true);
                        }
                    } else {  
                        st.pop();
                        st.push(true);
                    }
                } else {
                    st.push(false);
                }
            }
            
            return st.isEmpty();
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.