gpt4 book ai didi

创建递归二叉树?

转载 作者:行者123 更新时间:2023-12-04 06:41:41 25 4
gpt4 key购买 nike

我有两个堆栈,一个带有操作数,另一个带有运算符。我的问题是将这两个堆栈变成二叉树。

例如,表达式 (2+3)*(4-3)将被翻译成后缀(例如 24+43-* )然后放入两个堆栈3442*-+将是堆栈(顶部分别为 3 和 *)。

现在有了这些堆栈,我需要形成一个二叉树

   *
+ -
2 3 4 3

有没有办法递归地做到这一点?

现在,我有一个这样的算法:
  • 创建树的根,将根的值赋给运算符堆栈中的第一个运算符。将左右指针设置为空。
  • 创建正确的节点,如果存在则为其分配下一个运算符的值,如果不存在则为其分配一个操作数。然后对左节点执行相同操作。

  • 我的问题是使这个递归,或者让它处理许多不同的情况。

    谢谢你的帮助。

    最佳答案

    假设您只有二元运算符

    treeNode createNode(operators, operands) {
    // take first operator and create a new treeNode with it. pop it from the operators stack

    // if it is the last operator in the list then there should be only two operands left in the operands and you can assign them to the left and right child of the treeNode. return this treeNode.

    // if it is not the last operator then split the operands in two stacks equally
    // leftOperands and rightOperands
    // left child becomes createNode(operators, leftoperands)
    // right child becomes createNode(operators, rightoperands)
    // return this treeNode

    }

    关于创建递归二叉树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4155975/

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