As part of my assignment , I am given an expression tree and I need to convert it to a in-fix with O(n) run-time. For example,
To convert this tree to "( ( 1 V ( 2 H ( 3 V 4 ) ) ) H ( 5 V 6 ) )". I couldn't think of a way to convert it straight to infix so I thought of first converting it to post-fix and than to in-fix. (If there's a better way please tell me).
Now, my problem is with converting the tree to post-order. I have tried the following:
private String treeToPost(Node node, String post) {
if (node != null) {
treeToPost(node.left, post);
treeToPost(node.right, post);
post = post + node.data.getName();
}
return post;
}
Now I have two problems with this method, the first one is that doesn't work because it only saves the last node it traveled, the second one is that I'm not sure it will run at O(n) because it will have to create a new string each time. I found a solution to this issue here but it used StringBuilder which I am not allowed to use. I thought of making an array of chars to save the data , but because I dont know the size of the tree I cant know the size of the needed array. Thank you for your time :)