import java.util.*; /* * Given a valid binary tree representation as follows: * a tree might be represented as ( a b c ) where a is the root, b is the left * child and b is the right child. Any child/subtree can also be represented as * ( a ( b ) ( c ) ), ( a ( b ) c ), ( a b ( c ) ), etc.. * print the tree in in-order fashion */ public class InOrderBT { public static void main(String[] args){ String input = "( v ( a ( b ) ( ( c ) ( d ) ( x ( ) ) ) ) h )"; Scanner s = new Scanner( input); Stack stack = new Stack(); List lst = new ArrayList(); while(s.hasNext()){ String n = s.next(); if(n.equals(")")){ lst.clear(); while(!stack.peek().isOpenBracket()){ lst.add(0,stack.pop()); } //pop the "(" stack.pop(); if(lst.size() == 1){ TNode root = lst.get(0); stack.push(root); }else if(lst.size() == 2){ TNode root = lst.get(0); TNode left = lst.get(1); root.setLeft(left); stack.push(root); }else if(lst.size()==3){ TNode root = lst.get(0); TNode left = lst.get(1); TNode right = lst.get(2); root.setLeft(left); root.setRight(right); stack.push(root); } }else stack.push(new TNode(n)); } TNode.inOrderTraverse(stack.pop()); } } class TNode{ TNode left; TNode right; String v; public TNode(String v, TNode left, TNode right){ this.v = v; this.left = left; this.right = right; } public TNode(String v){ this.v = v; } public void setLeft(TNode n){ this.left = n;} public void setRight(TNode n){ this.right = n;} public boolean isOpenBracket(){ return v.equals("("); } public String toString(){ if(this.v == null) return ""; return "[ " + this.v + " left : " + ( left == null ? "null" : this.left.v ) + " right:" + ( right == null ? "null" : this.right.v) + "]"; } public static void inOrderTraverse(TNode node){ if(node == null) return; inOrderTraverse(node.left); System.out.print( node.v + " " ); inOrderTraverse(node.right); } }