从代数表达式创建二叉树

发布于 2024-12-11 05:22:59 字数 343 浏览 0 评论 0原文

我必须用 Java 创建一个算术计算器。为此,我必须解析二叉树中的代数表达式,然后计算并返回结果。那么第一步如何解析二叉树中的表达式?我知道这个理论,但我的问题是如何在 Java 中做到这一点。我读了下面的帖子 创建递归二叉树

但是我缺少基本的技巧或方法。我知道如何创建一个节点(我有一个类,其中包含 returnNodeValue、isLeaf、isDoubleNode、isSingleNode 等方法),但我认为我需要一个方法来在二叉树中插入节点来实现我想要的。有什么想法吗?

I have to create an arithmetic evaluator in Java. To do this I have to parse an algebric expression in binary tree and then calculate and return the result. So for the first step how can I parse an expression in a binary tree? I know the theory but my prob is how to do it in Java. I read the following post
create recursive binary tree

But I'm missing the basic trick or method. I know how to create a node (I have a class with methods like returnNodeValue, isLeaf, isDoubleNode, isSingleNode etc) but I think I'll need a method to insert a node in a binary tree to acheive what I want. Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

日暮斜阳 2024-12-18 05:22:59

前缀表达式的树结构

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

Apply (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

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

Tree construction for prefix expressions

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

Let's do an example: + 2 + 1 1

Apply (0).

  +

Apply (1).

  +
 /
2 

Apply (2).

  +
 / \
2   +

Apply (1).

  +
 / \
2   +
   /
  1 

Finally, apply (2).

  +
 / \
2   +
   / \
  1   1

This algorithm has been tested against - * / 15 - 7 + 1 1 3 + 2 + 1 1

So the Tree.insert implementation is those three rules.

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 = ?

Evaluating the tree is a little funny, because you have to start from the bottom-right of the tree. Perform a reverse post-order traversal. Visit the right child first.

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

Given the simplicity of constructing a tree from a prefix expression, I'd suggest using the standard stack algorithm to convert from infix to prefix. In practice you'd use a stack algorithm to evaluate an infix expression.

酷遇一生 2024-12-18 05:22:59

我认为您可能对自己应该做什么感到有点困惑:

...但我想我需要一种在二叉树中插入节点的方法...

您所说的二叉树实际上是一个解析树,并且它不是严格意义上的二叉树(因为并非所有树节点是二进制的)。 (除了“二叉树”具有二叉搜索树的含义,而这根本不是您在这里需要的。)

您已经弄清楚如何解析表达式,解析树的构造非常漂亮直截了当。例如:

Tree parseExpression() {
    // ....
    // binary expression case:
        Tree left = parseExpression();
        // parse operator
        Tree right = parseExpression();
        // lookahead to next operator
        if (...) {
        } else {
            return new BinaryNode(operator, left, right);
        }
     // ...
}

注意:这不是工作代码...这是帮助您做作业的提示。

I think you might be a bit confused about what you are supposed to be doing:

... but I think I'll need a method to insert a node in a binary tree ...

The binary tree you are talking about is actually a parse tree, and it is not strictly a binary tree (since not all tree nodes are binary). (Besides "binary tree" has connotations of a binary search tree, and that's not what you need here at all.)

One you have figured out to parse the expression, the construction of the parse tree is pretty straight-forward. For instance:

Tree parseExpression() {
    // ....
    // binary expression case:
        Tree left = parseExpression();
        // parse operator
        Tree right = parseExpression();
        // lookahead to next operator
        if (...) {
        } else {
            return new BinaryNode(operator, left, right);
        }
     // ...
}

Note: this is not working code ... it is a hint to help you do your homework.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文