简体   繁体   English

如何将 go 返回到二叉树中的预访问节点(前序遍历,解决 LeetCode 中的 No.1028 问题)

[英]How to go back to pre-visited node in a binary tree (preorder traversal, solving No.1028 problem in LeetCode )

I'm struggling to solving No.1028 problem in LeetCode by myself.我正在努力自己解决 LeetCode 中的 No.1028 问题。 As a step of my solution, I wanna construct a binary tree below by adding nodes one by one in an order of 'preorder traversal'.作为我的解决方案的一个步骤,我想通过按“前序遍历”的顺序一个接一个地添加节点来构造一个二叉树。

在此处输入图像描述

When I'm done with leftmost nodes with moving the cursor., now I'm supposed to add 'TreeNode(5)' as a right child node of 'TreeNode(2)'.当我通过移动 cursor 完成最左边的节点时,现在我应该添加“TreeNode(5)”作为“TreeNode(2)”的右子节点。

class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

root = TreeNode(1)
# cursor = root
# Add TreeNode(N) as a childNode
# cursor = cursor.left
# ...repeat
# Now cursor reaches TreeNode(4)

However, I have no idea of bactracking to the pre-visited nodes.但是,我不知道回溯到预先访问的节点。 I tried to do so by stacking pre-visited nodes in my stack and popping few times.我试图通过在我的堆栈中堆叠预先访问的节点并弹出几次来做到这一点。

tmp = [TreeNode(1), TreeNode(2), TreeNode(3), TreeNode(4)]
tmp.pop()
tmp.pop()

cursor = tmp.pop()

But only to fail since cursor does contain TreeNode(2) but the tree-relationship between nodes are deleted (I know actually they are not deleted but just cursor becomes another class object).但只是失败,因为 cursor 确实包含 TreeNode(2) 但节点之间的树关系被删除(我知道实际上它们没有被删除,但只是 cursor 成为另一个 ZA2F2ED4F8EBC2CBB4C21A29DC40AB61 对象)。

Could anyone let me know how to visit parent node?谁能告诉我如何访问父节点?

I tried to do so by stacking pre-visited nodes in my stack and popping few times.我试图通过在我的堆栈中堆叠预先访问的节点并弹出几次来做到这一点。

That really is the way to do it.这才是真正的方法。

tmp = [TreeNode(1), TreeNode(2), TreeNode(3), TreeNode(4)]

You should only create nodes as you process them from the input, and append them to the stack (using stack.append(node) ).您应该只在从输入处理节点时创建节点,并将 append 节点放入堆栈(使用stack.append(node) )。 Don't recreate nodes, as those will be different objects.不要重新创建节点,因为它们将是不同的对象。

Before appending the node to the stack, you should first verify what the level is you get from the input.在将节点附加到堆栈之前,您应该首先验证您从输入中获得的级别 That should become the size of the stack -- so if the stack is larger than the level, then pop elements from it until the stack has the right size.这应该成为堆栈的大小 - 因此,如果堆栈大于级别,则从中弹出元素,直到堆栈具有正确的大小。 Only then append the new node to the stack.只有 append 将新节点添加到堆栈中。

Finally, you need to establish the relationship between new node and its parent.最后,您需要建立新节点与其父节点之间的关系。 Its parent is the preceding node on the stack.它的父节点是堆栈上的前一个节点。 Remains to find out whether the new node should become a left child or a right child.剩下的就是找出新节点应该成为孩子还是孩子。 If the parent happens to already have a left child, then make the new node the right child of the parent, otherwise it should become the left child.如果父节点恰好已经有一个左子节点,则使新节点成为父节点的右子节点,否则它应该成为左子节点。

With these ingredients you should be able to code it.使用这些成分,您应该能够对其进行编码。

Here is a spoiler solution:这是一个扰流板解决方案:

import re # Use regular expression to easily tokenise the input class Solution: def recoverFromPreorder(self, s): stack = [] for dashes, valstr in re.findall("(-*)(\d+)", s): level = len(dashes) node = TreeNode(int(valstr)) del stack[level:] # Potentially truncate the stack if level: # This node has a parent: establish link if not stack[-1].left: stack[-1].left = node else: stack[-1].right = node stack.append(node) return stack[0] # Test run root = Solution().recoverFromPreorder("1-2--3---4-5--6---7")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM