gpt4 book ai didi

tree - 我可以在没有递归和堆栈的情况下对二叉树进行中序遍历吗?

转载 作者:行者123 更新时间:2023-12-04 20:59:17 27 4
gpt4 key购买 nike

任何人都可以给我一个在没有递归和不使用堆栈的情况下按顺序遍历二叉树的解决方案吗?

最佳答案

第二次编辑:我认为这是正确的。除了通常的 node.left_child 和 node.right_child 之外,还需要 node.isRoot、node.isLeftChild 和 node.parent。

state = "from_parent"
current_node = root
while (!done)
switch (state)
case "from_parent":
if current_node.left_child.exists
current_node = current_node.left_child
state = "from_parent"
else
state = "return_from_left_child"
case "return_from_left_child"
if current_node.right_child.exists
current_node = current_node.right_child
state = "from_parent"
else
state = "return_from_right_child"
case "return_from_right_child"
if current_node.isRoot
done = true
else
if current_node.isLeftChild
state = "return_from_left_child"
else
state = "return_from_right_child"
current_node = current_node.parent

关于tree - 我可以在没有递归和堆栈的情况下对二叉树进行中序遍历吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2595002/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com