GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • LeetCodeJavascript.com
  • Star on GitHub

This view

  • Original page
  • New address

GeezerVison is showing leetcodejavascript.com — #606 - Construct String from Binary Tree - LeetCode JavaScript Solutions

Back to all solutions

#606 - Construct String from Binary Tree

Easy • View on LeetCode • View on GitHub
String Depth-First Search Tree Binary Tree

Problem Description

You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.

The null node needs to be represented by empty parenthesis pair "()".

And you need to omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree.

Solution

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} t
 * @return {string}
 */
var tree2str = function(t) {
  return !t ? '' : `${t.val}(${tree2str(t.left)})(${tree2str(t.right)})`.replace(/(\(\)){2}|\(\)(?=$|\))/g, '');
};


// alternative, longer but faster version:
/**
 * @param {TreeNode} t
 * @return {string}
 */
var tree2str = function(t) {
  let str = t ? `${t.val}` : '';
  if (t && t.right) str += `(${tree2str(t.left)})(${tree2str(t.right)})`;
  else if (t && t.left) str += `(${tree2str(t.left)})`;
  return str;
};
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.