由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - 问一道多叉树的面试题 非递归实现
进入JobHunting版参与讨论
1 (共1页)
b********n
发帖数: 1
1
贴在了stackoverflow上, 今天面某大厂被问的
https://stackoverflow.com/questions/71273541/convert-a-n-ary-tree-from-
bottom-up-without-recursion
n******g
发帖数: 2201
2
思路就是用一个栈

【在 b********n 的大作中提到】
: 贴在了stackoverflow上, 今天面某大厂被问的
: https://stackoverflow.com/questions/71273541/convert-a-n-ary-tree-from-
: bottom-up-without-recursion

b********n
发帖数: 1
3
怎么写,和网上其它的原题不太一样

【在 n******g 的大作中提到】
: 思路就是用一个栈
n******g
发帖数: 2201
4
本办法吧tree变成图
然后post order dfs 我没仔细想

【在 b********n 的大作中提到】
: 怎么写,和网上其它的原题不太一样
l******r
发帖数: 1
5
用3个stack
前两个得倒postorder的顺序,然后从postorder stack里面一个node一个node取,
convert之后再放入stack。
python 代码
------------
from __future__ import annotations
from typing import List
class NodeTypeA:
def __init__(self, payload: str, children : List[NodeTypeA] = []):
self.payload = payload
self.children = children
class NodeTypeB:
def __init__(self, payload: str, children : List[NodeTypeB] = []):
self.payload = payload
self.children = children
def convertLeaf(node: NodeTypeA)->NodeTypeB:
print(f"Converting Leaf NodeTypeA {node.payload}")
return NodeTypeB(node.payload)
def convertParent(node: NodeTypeA, childrenB: List[NodeTypeB])->NodeTypeB:
print(f"Converting Parent NodeTypeA {node.payload}")
return NodeTypeB(node.payload, children = childrenB)
class Solution:
def convert(self, node: NodeTypeA)->None:
if node == None:
return
if len(node.children) == 0:
convertLeaf(node)
return
childrenB = []
for child in node.children:
childrenB.append(self.convert(child))
convertParent(node, childrenB)
return
def convert_iterative(self, node:NodeTypeA)->None:
stack = []
stack.append(node)
postorder_stack = []
while stack:
node = stack.pop()
postorder_stack.append(node)
for child in node.children:
stack.append(child)
child_stack = []
while postorder_stack:
node = postorder_stack.pop()
if len(node.children) == 0:
child_stack.append(convertLeaf(node))
else:
size = len(node.children)
nodeBs = []
while size > 0:
nodeBs.append(child_stack.pop())
size -= 1
child_stack.append(convertParent(node, nodeBs[::-1]))
return

if __name__ == "__main__":
n1 = NodeTypeA(1)
n2 = NodeTypeA(2)
n3 = NodeTypeA(3)
n4 = NodeTypeA(4)
n5 = NodeTypeA(5)
n6 = NodeTypeA(6)
n7 = NodeTypeA(7)
n8 = NodeTypeA(8)
n9 = NodeTypeA(9)
n10 = NodeTypeA(10)
n11 = NodeTypeA(11)
n12 = NodeTypeA(12)
n13 = NodeTypeA(13)
n1.children = [n2, n3, n4]
n2.children = [n5, n6]
n4.children = [n7, n8, n9]
n5.children = [n10]
n6.children = [n11, n12, n13]
sol = Solution()
sol.convert_iterative(n1)


【在 b********n 的大作中提到】
: 贴在了stackoverflow上, 今天面某大厂被问的
: https://stackoverflow.com/questions/71273541/convert-a-n-ary-tree-from-
: bottom-up-without-recursion

1 (共1页)
进入JobHunting版参与讨论