栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从代数表达式创建二叉树

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从代数表达式创建二叉树

前缀表达式的树结构

def insert     Insert each token in the expression from left to right:     (0) If the tree is empty, the first token in the expression (must         be an operator) becomes the root     (1) Else if the last inserted token is an         operator, then insert the token as the left child of the last inserted         node.     (2) Else if the last inserted token is an operand, backtrack up the         tree starting from the last inserted node and find the first node with a NULL         right child, insert the token there. **Note**: don't insert into the last inserted          node. end def

让我们做一个例子:

+ 2 + 1 1

套用(0)。

  +

套用(1)。

  + /2

套用(2)。

  + / 2   +

套用(1)。

  + / 2   +   /  1

最后,应用(2)。

  + / 2   +   /   1   1

该算法已针对

- * / 15 - 7 + 1 1 3 + 2 + 1 1

因此

Tree.insert
执行就是这三个规则。

insert(rootNode, token)  //create new node with token  if (isLastTokenOperator)//case 1      //insert into last inserted's left child  else {       //case 2      //backtrack: get node with NULL right child      //insert  }  //maintain state  lastInsertedNode = ?, isLastTokenOperator = ?

评估树有点有趣,因为您必须从树的右下角开始。执行反向后置遍历。首先拜访合适的孩子。

evalPostorder(node)  if (node == null) then return 0  int rightVal = evalPostorder(node.right)  int leftVal = evalPostorder(node.left)  if(isOperator(node.value))        return rightVal <operator> leftVal      else       return node.value

考虑到从前缀表达式构造树的简单性,我建议使用标准堆栈算法将中缀转换为前缀。在实践中,您将使用堆栈算法来计算中缀表达式。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/463369.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号