主体
今天刷 leetcode 题时,偶然发现了一个简单好用的方法来打印树——重写Java的 toString() 方法:
public String toString() {
if (left == null && right == null) {
return String.format("[ %d ]", val);
}
return String.format("[ %d : %s, %s]", val, left, right);
}
测试打印这棵满二叉树
这个 toString() 方法里用的是先序遍历,你可以更改为中序或后续遍历,甚至,你可以改写成返回一个 JSON字符串。
源码
这里顺带贴个我写的二叉树源码吧,虽然都很简单
TreeNode.java
package base.tree;
import java.util.Objects;
/**
* TreeNode
*/
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
/** 先序遍历 */
@Override
public String toString() {
if (left == null && right == null) {
return String.format("[ %d ]", val);
}
return String.format("[ %d : %s, %s]", val, left, right);
}
@Override
public int hashCode() {
return Objects.hash(val);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof TreeNode))
return false;
TreeNode other = (TreeNode) obj;
return val == other.val;
}
}
BinaryTree.java
package base.tree;
/**
* Tree
*/
public class BinaryTree {
private TreeNode root;
private int size = 0;
public BinaryTree(int val){
this(new TreeNode(val));
}
public BinaryTree( TreeNode node ) {
root = node;
size++;
}
public void add(Integer val){
if(val == null){
addNode(null);
return;
}
addNode(new TreeNode(val));
}
public void addNode(TreeNode node){
TreeNode parent = get((size+1) / 2);
if( size % 2 == 1 ){ //要插入的节点在左边
parent.left = node;
}else{
parent.right = node;
}
size++;
}
public TreeNode root(){
return root;
}
public int depth(){
return depth(size);
}
public int depth(int i){
return (int) Math.ceil(Math.log(i + 1) / Math.log(2));
}
public int size(){
return size;
}
/** index begin from 1 not 0 */
public TreeNode get(int i){
char[] path = new char[depth(i) - 1];
for(int j = path.length - 1; j >= 0; j--){
path[j] = i % 2 == 0 ? 'l' : 'r';
i /= 2;
}
TreeNode node = root;
for(int j = 0; j < path.length; j++){
if(path[j] == 'l'){
node = node.left;
}else{
node = node.right;
}
}
return node;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("BinaryTree [root=").append(root).append(", size=").append(size)
.append(", depth=").append(depth()).append("]");
return builder.toString();
}
}
测试
// 构建树
BinaryTree tree = new BinaryTree(2);
Stream.of(3,3,4,5,5,4,null,8,9,9,8,null).forEach(tree::add);
// 打印树
System.out.println("this tree is");
System.out.println(tree);
this tree is
BinaryTree [root=[ 2 : [ 3 : [ 4 : null, [ 8 ]], [ 5 : [ 9 ], [ 9 ]]], [ 3 : [ 5 : [ 8 ], null], [ 4 ]]], size=13, depth=4]