Last active
October 9, 2018 09:10
-
-
Save wangshuai1992/5434fde2653a7e5e1a88f0eda15e08bc to your computer and use it in GitHub Desktop.
控制台直观打印二叉树
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class TreeNode { | |
int val; | |
TreeNode left; | |
TreeNode right; | |
TreeNode(int x) { | |
val = x; | |
} | |
/** | |
* 将树转换成字符串并打印在控制台上,用L表示左孩子,R表示右孩子 | |
*/ | |
public void print() { | |
List<TreeNode> tree = locateNodes(); | |
int size = tree.size(); | |
int deepth = 0; | |
// 获取树的深度 | |
while ((size >>= 1) > 0) { | |
deepth++; | |
} | |
deepth++; | |
Iterator<TreeNode> iterator = tree.iterator(); | |
int maxPosition = 1; | |
// 层数,从1开始 | |
for (int floor = 1; floor <= deepth; floor++) { | |
maxPosition = 1 << (floor - 1); | |
printBlank((1 << (deepth - floor)) - 1); | |
for (int position = 0; position < maxPosition; position++) { | |
if (iterator.hasNext()) { | |
TreeNode node = iterator.next(); | |
if (node != null) { | |
System.out.print(node); | |
} else { | |
System.out.print(" "); | |
} | |
printBlank((1 << (deepth - floor + 1)) - 1); | |
} | |
} | |
System.out.println(); | |
} | |
} | |
/** | |
* 将二叉树用空节点补充成完全二叉树,并以水平遍历形式返回 | |
* | |
* @return | |
*/ | |
private List<TreeNode> locateNodes() { | |
Queue<TreeNode> queue = new LinkedList<>(); | |
// 把树补充成完全二叉树,放在这个链表中 | |
List<TreeNode> tree = new LinkedList<>(); | |
queue.add(this); | |
// 队列中非空节点数 | |
int nodeCount = 1; | |
while (!queue.isEmpty() && nodeCount > 0) { | |
TreeNode node = queue.remove(); | |
if (node != null) { | |
nodeCount--; | |
tree.add(node); | |
TreeNode leftNode = node.left; | |
TreeNode rightNode = node.right; | |
if (leftNode == null) { | |
queue.add(null); | |
} else { | |
queue.add(leftNode); | |
nodeCount++; | |
} | |
if (rightNode == null) { | |
queue.add(null); | |
} else { | |
queue.add(rightNode); | |
nodeCount++; | |
} | |
} else { | |
tree.add(null); | |
queue.add(null); | |
queue.add(null); | |
} | |
} | |
return tree; | |
} | |
private void printBlank(int length) { | |
while (length-- > 0) { | |
System.out.print(" "); | |
} | |
} | |
@Override | |
public String toString() { | |
return "" + val; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment