JAVA preOrder with separator


  • 0
    B
        public String serialize(TreeNode root) {
    
            if (root == null)
                return "";
                
            //do preOrder
            StringBuffer ret = new StringBuffer();
            
            ret.append(root.val).append("#").append(serialize(root.left)).append(serialize(root.right));
            
            return ret.toString();
            
        }
        
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            String[] tree = data.split("#");
            
            TreeNode root = null;
            
            for (String val : tree){
                
                if (val.length() == 0)
                    continue;
                
                int i = Integer.valueOf(val);
                TreeNode node = new TreeNode(i);
                
                if (root == null)
                    root = node;
                else{
    
                    TreeNode temp = root;
    
                    while (true){
                        if (i < temp.val)
                            if (temp.left == null){
                                temp.left = node;
                                break;
                            }else
                                temp = temp.left;
                        else
                            if (temp.right == null){
                                temp.right = node;
                                break;
                            }else
                                temp = temp.right;
                        
                        
                    }
                    
                }
                
            }
            
            return root;
        }
    

Log in to reply
 

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