0
以下設計是否可以進一步優化?我使用了一個hashmap和一個Queue。 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());
}
}
看樣子你需要遍歷每個節點,所以我看不到複雜性如何爲O少( N)。你可以做的是使用StringBuilder,而不是附加到一個字符串。 – 2012-08-13 14:26:16
你爲什麼要從循環中的散列表中刪除節點,你是否只打印最低的樹節點? – 2012-08-13 14:28:17
這不能在'O(N * Log N)'下完成,因爲你有'N * Log N'項目需要打印。 – dasblinkenlight 2012-08-13 14:37:32