113. Virtual DOM I

medium  - accepted / - tried

Suppose you have solved 110. serialize and deserialize binary tree, have you wondered how to do similar task to DOM tree ?

HTML string could be thought as some sort of serialization, the browser parses(deserialize) the HTML → construct the DOM tree.

Besides XML base, we could try JSON for this. If we log the element presentation in React, like below

const el = <div> <h1> this is </h1> <p className="paragraph"> a <button> button </button> from <a href="https://bfe.dev"><b>BFE</b>.dev</a> </p></div>;console.log(el)

we would get this( ref, key .etc are stripped off)

{  type: 'div',  props: {    children: [      {        type: 'h1',        props: {          children: ' this is '        }      },      {        type: 'p',        props: {          className: 'paragraph',          children: [            ' a ',            {              type: 'button',              props: {                children: ' button '              }            },            ' from',            {              type: 'a',              props: {                href: 'https://bfe.dev',                children: [                  {                    type: 'b',                    props: {                      children: 'BFE'                    }                  },                  '.dev'                ]              }            }          ]        }      }    ]  }}

Clearly this is the same tree structure but only in object literal.

Now you are asked to serialize/deserialize the DOM tree, like what React does.


Functions like event handlers and custom components are beyond the scope of this problem, you can ignore them, just focus on basic HTML tags.

You should support:

  1. TextNode (string) as children
  2. single child and multiple children
  3. camelCased properties.

virtualize() takes in a real DOM tree and create an object literal render() takes in a object literal presentation and recreate a DOM tree.

What is time & space complexity of your approach?