LeetCode 1028 Recover a Tree From Preorder Traversal (栈 或 DFS 推荐)

We run a preorder depth first search 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 S of this traversal, recover the tree and return its root.

Example 1:

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

Example 2:

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

Example 3:

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

Note:

  • The number of nodes in the original tree is between 1and 1000.
  • Each node will have a value between 1 and 10^9.

题目链接:https://leetcode.com/problems/recover-a-tree-from-preorder-traversal/

题目分析:一开始上来的思路比较直接,先把每个结点的值和深度记录下来,然后用两个栈模拟先序遍历的过程,一个栈用来存从输入中解析出的结点,一个栈用来存当前构造出来的TreeNode

11ms,时间击败22%

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    class Node {
        int val;
        int deep;
        public Node(int val, int deep) {
            this.val = val;
            this.deep = deep;
        }
    }
    
    public List<Node> getNodes(String S) {
        List<Node> ans = new ArrayList<>();
        int i = 0, deep = 0, val = 0;
        while (i < S.length()) {
            while (i < S.length() && S.charAt(i) >= '0' && S.charAt(i) <= '9') {
                val = val * 10 + (S.charAt(i) - '0');
                i++;
            }
            ans.add(new Node(val, deep));
            deep = 0;
            val = 0;
            while (i < S.length() && S.charAt(i) == '-') {
                deep++;
                i++;
            }
        }
        return ans;
    }
    
    public void recover(TreeNode root, List<Node> nodes) {
        Stack<Node> stk = new Stack<>();
        Stack<TreeNode> tstk = new Stack();
        stk.push(nodes.get(0));
        tstk.push(root);
        int pos = 1;
        while (!stk.empty() && pos < nodes.size()) {
            while (!stk.empty() && stk.peek().deep + 1 != nodes.get(pos).deep) {
                stk.pop();
                tstk.pop();
            }
            root = tstk.peek();
            while (root.left == null && pos < nodes.size() && stk.peek().deep + 1 == nodes.get(pos).deep) {
                root.left = new TreeNode(nodes.get(pos).val);
                stk.push(nodes.get(pos));
                tstk.push(root.left);
                pos++;
                root = root.left;
            }
        
            if (root.right == null && pos < nodes.size() && stk.peek().deep + 1 == nodes.get(pos).deep) {
                root.right = new TreeNode(nodes.get(pos).val);
                stk.push(nodes.get(pos));
                tstk.push(root.right);
                pos++;
                root = root.right;
            }
        }
    }
    
    public TreeNode recoverFromPreorder(String S) {
        List<Node> nodes = getNodes(S);
        TreeNode root = new TreeNode(nodes.get(0).val);
        recover(root, nodes);
        return root;
    }
}

能用栈自然也能用递归咯,递归版

6ms,时间击败71.15%

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    class Node {
        int val;
        int deep;
        public Node(int val, int deep) {
            this.val = val;
            this.deep = deep;
        }
    }
    
    public List<Node> getNodes(String S) {
        List<Node> ans = new ArrayList<>();
        int i = 0, deep = 0, val = 0;
        while (i < S.length()) {
            while (i < S.length() && S.charAt(i) >= '0' && S.charAt(i) <= '9') {
                val = val * 10 + (S.charAt(i) - '0');
                i++;
            }
            ans.add(new Node(val, deep));
            deep = 0;
            val = 0;
            while (i < S.length() && S.charAt(i) == '-') {
                deep++;
                i++;
            }
        }
        return ans;
    }
    
    int pos = 1;
    
    public void recover(TreeNode root, Node pre, List<Node> nodes) {
        if (pos == nodes.size()) {
            return;
        }
        Node cur = nodes.get(pos);
        if (cur.deep == pre.deep + 1) {
            root.left = new TreeNode(cur.val);
            pos++;
            recover(root.left, cur, nodes);   
        }
        if (pos < nodes.size()) {
            cur = nodes.get(pos);
            if (cur.deep == pre.deep + 1) {
                root.right = new TreeNode(cur.val);
                pos++;
                recover(root.right, cur, nodes);   
            }
        }
    }
    
    public TreeNode recoverFromPreorder(String S) {
        List<Node> nodes = getNodes(S);
        TreeNode root = new TreeNode(nodes.get(0).val);
        recover(root, nodes.get(0), nodes);
        return root;
    }
}

时间最优的解法应该是在DFS的过程中计算深度,而非提前记录下来

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用\[1\]提供了一个朴素的解法,使用两个来存储字符串,一个用来存储普通字符,另一个用来存储特殊字符。遍历字符串,如果是普通字符则压入第一个,如果是特殊字符则弹出第一个顶元素。最后比较两个是否相同即可判断字符串是否有效。这个解法的时间复杂度是O(M + N),空间复杂度也是O(M + N)。\[1\] 引用\[2\]提供了另一个的应用场景,即判断括号是否有效。遍历字符串,如果是左括号则压入,如果是右括号则判断和顶元素是否匹配,不匹配则返回false,匹配则弹出顶元素。最后判断是否为空即可判断括号是否有效。\[2\] 引用\[3\]也提供了一个判断括号是否有效的解法,使用来操作。遍历字符串,如果是左括号则压入,如果是右括号则判断和顶元素是否匹配,不匹配则返回false,匹配则弹出顶元素。最后判断是否为空即可判断括号是否有效。这个解法使用了HashMap来存储括号的对应关系。\[3\] 综上所述,在解决字符串相关问题中有着广泛的应用,包括判断字符串是否有效、逆波兰表达式等。在解决这些问题时,可以帮助我们保存和处理字符的顺序,从而简化问题的处理过程。 #### 引用[.reference_title] - *1* *3* [Leetcode刷题03-](https://blog.csdn.net/weixin_47802917/article/details/123007699)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v4^insert_chatgpt"}} ] [.reference_item] - *2* [leetCode-类型详解](https://blog.csdn.net/zhiyikeji/article/details/125508011)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v4^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值