Java如何从字符串填充二叉树 [英] How to fill a binary tree from a string, java

查看:44
本文介绍了Java如何从字符串填充二叉树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据这样的字符串,用整数填充二叉树.

I'm suppose to fill a binary tree with integers based upon a string like this.

 [int](LT)(RT)

LT是树左侧的相同形式的表达式.与RT相同.一个有效的字符串应该是这样的: 4(2(1)(3))(6(5)(7).我怎么填充这棵树?这样,它就可以用节点填充每个级别".谢谢您的帮助.

LT is an expression of the same form for the left part of the tree. Same with RT. A valid string would be something like this: 4(2(1)(3))(6(5)(7). How can I fill this tree? This is not a sorted tree of any kind. So it can just fill every "level" with nodes. Thank you for help.

推荐答案

您必须为此创建一个解析器,并使用解析器中的指令填充某种数据结构.

You have to create a parser for that and fill some kind of data structure with the instructions from your parser.

然后,当数据结构填充完毕时,只需将其推入树中即可.

Then when your data structure is filled you just push it into the tree.

大致情况:

 Structure s = Parser.parse("4(2(1)(3))(6(5)(7)");

然后迭代结构.

  Tree binaryTree = ...

  for( Instruction i : s ) {

      if( i.leaf == Tree.LEFT ) {
          tree.addLeft( i.value );
      } else if ( i.leaf == Tree.RIGHT ) {
           tree.addRight( i.value );
      }
  }

这篇关于Java如何从字符串填充二叉树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆