本文介绍了如何把后缀EX pressions二叉树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个二叉树和前后缀pression6 2 * 3 /什么是算法中把它在树上?喜欢,

  [/]
          / \
        [*] [3]
        / \
      [6] [2]
 

解决方案

要构建从ex pression,pretend您直接评估它在树上,但构建计算数字的树来代替。 (这招适用于许多比前后缀pressions更多的东西。)

算法:有一个堆栈来存储中间值(这是树),并检查每个令牌从左至右:

  • 如果它是一个数字,把它变成一个叶子结点,并将其推入堆栈。
  • 如果它是一个操作符,弹出两个项目从堆栈,构建与子女的操作员节点,并推动新的节点在堆栈上。

最后,如果EX pression正确形成,那么你应该有一个确切的树的栈是整个EX pression树的形式。

so i have a binary tree and a postfix expression "6 2 * 3 /"what is the algo to put it in a tree?like,

          [/]
          / \
        [*]  [3]
        / \
      [6] [2]
解决方案

To construct a tree from the expression, pretend you are evaluating it directly but construct trees instead of calculating numbers. (This trick works for many more things than postfix expressions.)

Algorithm: Have a stack to store intermediate values (which are trees), and examine each token from left to right:

  • If it is a number, turn it into a leaf node and push it on the stack.
  • If it is an operator, pop two items from the stack, construct an operator node with those children, and push the new node on the stack.

At the end, if the expression is properly formed, then you should have exactly one tree on the stack which is the entire expression in tree form.

这篇关于如何把后缀EX pressions二叉树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 02:24