java solution using stack


  • 0
    2
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Codec {
    
        // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            if (root == null) {
                return "NULL";
            }
            StringBuilder sb = new StringBuilder();
            Stack<TreeNode> s = new Stack<TreeNode>();
            s.push(root);
            while (!s.isEmpty()) {
                TreeNode t = s.pop();
                if (t != null) {
                    sb.append(t.val);
                    sb.append(" ");
                    s.push(t.right);
                    s.push(t.left);
                }
            }
            return sb.toString();
        }
    
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            if (data.equals("NULL")) {
                return null;
            }
            String[] token = data.substring(0, data.length() - 1).split(" ");
            Stack<TreeNode> st = new Stack<TreeNode>();
            Stack<Integer> si = new Stack<Integer>();
            TreeNode root = new TreeNode(Integer.parseInt(token[0]));
            st.push(root);
            si.push(Integer.MAX_VALUE);
            for (int i = 1; i < token.length; i++) {
                int val = Integer.parseInt(token[i]);
                while (val > si.peek()) {
                    st.pop();
                    si.pop();
                }
                TreeNode t = st.peek();
                if (val < t.val) {
                    t.left = new TreeNode(val);
                    st.push(t.left);
                    si.push(t.val);
                }
                else {
                    t.right = new TreeNode(val);
                    st.push(t.right);
                    si.push(si.peek());
                }
            }
            return root;
        }
    }
    
    // Your Codec object will be instantiated and called as such:
    // Codec codec = new Codec();
    // codec.deserialize(codec.serialize(root));
    

Log in to reply
 

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