创建递归二叉树?

编程入门 行业动态 更新时间:2024-10-28 10:23:29
本文介绍了创建递归二叉树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个烟囱,其中一个操作数,其他的与运营商。我的问题是转向这两个堆栈成二进制树。

I have two stacks, one with operands, the other with operators. My problem is turning these two stacks into a binary tree.

例如,前pression (2 + 3)*(4-3)将被翻译成后缀(这样 24 + 43 - * ),然后放入两个栈 3442 和。* - + 将在堆栈(带顶部分别为3和*)

For example, the expression (2+3)*(4-3) will be translated into postfix ( such that 24+43-*) and then put into two stacks 3442 and *-+ will be the stacks (with the tops being 3 and * respectively).

现在这些书库,我需要形成一个二叉树像

Now with these stacks, i need to form a binary tree like

* + - 2 3 4 3

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

Is there a way to do this recursively?

现在,我有一个算法,像这样:

Right now, I have an algorithm like so:

  • 创建树的根,根的值分配给在操作栈的第一个操作符。设置为NULL左右指针。

  • Create the root of the tree, assign the value of the root to the first operator in the operator-stack. Set the right and left pointers to null.

创建合适的节点,如果存在分配下一个运营商的价值,如果不给它分配一个操作数。然后为左节点执行相同

Create the right node, assign the value of the next operator if it exists, if not assign it an operand. Then do the same for the left node.

我的问题是使这个递归,或得到它来处理很多不同的情况。

My problem is making this recursive, or getting it to handle the many different cases.

感谢您的帮助。

推荐答案

假设你只有二元运算

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 }

更多推荐

创建递归二叉树?

本文发布于:2023-11-30 18:15:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651023.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   二叉树

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!