返回介绍

solution / 0500-0599 / 0536.Construct Binary Tree from String / README_EN

发布于 2024-06-17 01:03:59 字数 5828 浏览 0 评论 0 收藏 0

536. Construct Binary Tree from String

中文文档

Description

You need to construct a binary tree from a string consisting of parenthesis and integers.

The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root's value and a pair of parenthesis contains a child binary tree with the same structure.

You always start to construct the left child node of the parent first if it exists.

 

Example 1:

Input: s = "4(2(3)(1))(6(5))"
Output: [4,2,6,3,1,5]

Example 2:

Input: s = "4(2(3)(1))(6(5)(7))"
Output: [4,2,6,3,1,5,7]

Example 3:

Input: s = "-4(2(3)(1))(6(5)(7))"
Output: [-4,2,6,3,1,5,7]

 

Constraints:

  • 0 <= s.length <= 3 * 104
  • s consists of digits, '(', ')', and '-' only.

Solutions

Solution 1

# Definition for a binary tree node.
# class TreeNode:
#   def __init__(self, val=0, left=None, right=None):
#     self.val = val
#     self.left = left
#     self.right = right
class Solution:
  def str2tree(self, s: str) -> TreeNode:
    def dfs(s):
      if not s:
        return None
      p = s.find('(')
      if p == -1:
        return TreeNode(int(s))
      root = TreeNode(int(s[:p]))
      start = p
      cnt = 0
      for i in range(p, len(s)):
        if s[i] == '(':
          cnt += 1
        elif s[i] == ')':
          cnt -= 1
        if cnt == 0:
          if start == p:
            root.left = dfs(s[start + 1 : i])
            start = i + 1
          else:
            root.right = dfs(s[start + 1 : i])
      return root

    return dfs(s)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *   int val;
 *   TreeNode left;
 *   TreeNode right;
 *   TreeNode() {}
 *   TreeNode(int val) { this.val = val; }
 *   TreeNode(int val, TreeNode left, TreeNode right) {
 *     this.val = val;
 *     this.left = left;
 *     this.right = right;
 *   }
 * }
 */
class Solution {
  public TreeNode str2tree(String s) {
    return dfs(s);
  }

  private TreeNode dfs(String s) {
    if ("".equals(s)) {
      return null;
    }
    int p = s.indexOf("(");
    if (p == -1) {
      return new TreeNode(Integer.parseInt(s));
    }
    TreeNode root = new TreeNode(Integer.parseInt(s.substring(0, p)));
    int start = p;
    int cnt = 0;
    for (int i = p; i < s.length(); ++i) {
      if (s.charAt(i) == '(') {
        ++cnt;
      } else if (s.charAt(i) == ')') {
        --cnt;
      }
      if (cnt == 0) {
        if (start == p) {
          root.left = dfs(s.substring(start + 1, i));
          start = i + 1;
        } else {
          root.right = dfs(s.substring(start + 1, i));
        }
      }
    }
    return root;
  }
}
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *   int val;
 *   TreeNode *left;
 *   TreeNode *right;
 *   TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *   TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *   TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
  TreeNode* str2tree(string s) {
    return dfs(s);
  }

  TreeNode* dfs(string s) {
    if (s == "") return nullptr;
    int p = s.find("(");
    if (p == s.npos) return new TreeNode(stoi(s));
    TreeNode* root = new TreeNode(stoi(s.substr(0, p)));
    int start = p;
    int cnt = 0;
    for (int i = p; i < s.size(); ++i) {
      if (s[i] == '(')
        ++cnt;
      else if (s[i] == ')')
        --cnt;
      if (cnt == 0) {
        if (start == p) {
          root->left = dfs(s.substr(start + 1, i - start - 1));
          start = i + 1;
        } else
          root->right = dfs(s.substr(start + 1, i - start - 1));
      }
    }
    return root;
  }
};
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *   Val int
 *   Left *TreeNode
 *   Right *TreeNode
 * }
 */
func str2tree(s string) *TreeNode {
  var dfs func(s string) *TreeNode
  dfs = func(s string) *TreeNode {
    if s == "" {
      return nil
    }
    p := strings.IndexAny(s, "(")
    if p == -1 {
      v, _ := strconv.Atoi(s)
      return &TreeNode{Val: v}
    }
    v, _ := strconv.Atoi(s[:p])
    root := &TreeNode{Val: v}
    start := p
    cnt := 0
    for i := p; i < len(s); i++ {
      if s[i] == '(' {
        cnt++
      } else if s[i] == ')' {
        cnt--
      }
      if cnt == 0 {
        if p == start {
          root.Left = dfs(s[start+1 : i])
          start = i + 1
        } else {
          root.Right = dfs(s[start+1 : i])
        }
      }
    }
    return root
  }
  return dfs(s)
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文