override toString() function for TreeNode to output OJ's Binary Tree Serialization
1 class TreeNode { 2 int val; 3 TreeNode left; 4 TreeNode right; 5 TreeNode(int x) { val = x; } 6 7 @Override 8 public String toString(){ 9 if(this == null) return ""; 10 StringBuilder sb = new StringBuilder(); 11 LinkedList<TreeNode> queue = new LinkedList<TreeNode>(); 12 queue.add(this); 13 sb.append(val + ","); 14 while(!queue.isEmpty()){ 15 TreeNode tmp = queue.poll(); 16 sb.append((tmp.left == null ? "#" : tmp.left.val) + ","); 17 sb.append((tmp.right == null ? "#" : tmp.right.val) + ","); 18 if(tmp.left != null) queue.add(tmp.left); 19 if(tmp.right != null) queue.add(tmp.right); 20 } 21 return sb.toString(); 22 23 } 24 }
posted on 2015-03-26 10:38 Step-BY-Step 阅读(331) 评论(0) 编辑 收藏 举报