How to fill a binary tree from a string, java

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-24 21:34:16

问题


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

 [int](LT)(RT)

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.


回答1:


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.

Something along the lines:

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

And then iterate the structure.

  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 );
      }
  }



回答2:


grab the first number of the string, split on '(', strip the trailing ')', recursively repeat.




回答3:


Use a stack to keep track of the '(' and ')'

Push all the '(' onto the stack and pop off when you encounter ')'.

From there, you just have to decide how to interpret the in between stuff for yourself.



来源:https://stackoverflow.com/questions/1575349/how-to-fill-a-binary-tree-from-a-string-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!