下面的设计可以进一步优化吗?我使用了哈希图和队列。SO 空间复杂度为 O(n),运行时间为 O(n)
public class PrintAllRootToLeaves {
public static void print(BinaryTreeNode root) {
Queue nodesQ = new Queue();
HashMap hMap = new HashMap();
BinaryTreeNode head = root;
String tempVal ;
hMap.put(head,String.valueOf(head.getData()));
while (head != null) {
BinaryTreeNode left = head.getLeft();
BinaryTreeNode right = head.getRight();
if (left != null) {
if ((tempVal = (String) hMap.get(head)) != null) {
hMap.put(left,tempVal + left.getData());
}
nodesQ.enqueue(left);
}
if (right != null) {
if ((tempVal = (String) hMap.get(head)) != null) {
hMap.put(right,tempVal + right.getData());
}
nodesQ.enqueue(right);
}
if (right != null && left != null) {
hMap.remove(head);
}
head = (BinaryTreeNode) nodesQ.dequeue();
}
System.out.println("-----------Printing all routes ---------->" + hMap.values());
}
}