返回介绍

solution / 1000-1099 / 1028.Recover a Tree From Preorder Traversal / README_EN

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

1028. Recover a Tree From Preorder Traversal

中文文档

Description

We run a preorder depth-first search (DFS) on the root of a binary tree.

At each node in this traversal, we output D dashes (where D is the depth of this node), then we output the value of this node.  If the depth of a node is D, the depth of its immediate child is D + 1.  The depth of the root node is 0.

If a node has only one child, that child is guaranteed to be the left child.

Given the output traversal of this traversal, recover the tree and return _its_ root.

 

Example 1:

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

Example 2:

Input: traversal = "1-2--3---4-5--6---7"
Output: [1,2,5,3,null,6,null,4,null,7]

Example 3:

Input: traversal = "1-401--349---90--88"
Output: [1,401,null,349,88,90]

 

Constraints:

  • The number of nodes in the original tree is in the range [1, 1000].
  • 1 <= Node.val <= 109

Solutions

Solution 1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *   int val;
 *   TreeNode *left;
 *   TreeNode *right;
 *   TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
  TreeNode* recoverFromPreorder(string S) {
    stack<TreeNode*> st;
    int depth = 0;
    int num = 0;
    for (int i = 0; i < S.length(); ++i) {
      if (S[i] == '-') {
        depth++;
      } else {
        num = 10 * num + S[i] - '0';
      }
      if (i + 1 >= S.length() || (isdigit(S[i]) && S[i + 1] == '-')) {
        TreeNode* newNode = new TreeNode(num);
        while (st.size() > depth) {
          st.pop();
        }
        if (!st.empty()) {
          if (st.top()->left == nullptr) {
            st.top()->left = newNode;
          } else {
            st.top()->right = newNode;
          }
        }
        st.push(newNode);
        depth = 0;
        num = 0;
      }
    }
    TreeNode* res;
    while (!st.empty()) {
      res = st.top();
      st.pop();
    }
    return res;
  }
};

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

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

发布评论

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