0
我在Python中編碼Huffman樹。我有一個常規函數,它接受要編碼的字符串和霍夫曼樹。它創建一個字符串字符數組和一個空的數組,其條目將是每個char對應的二進制路徑。該函數遍歷字符串數組中的每個字符,調用函數2,遞歸搜索樹,建立二進制代碼並在找到字母后返回。通過樹正確的遞歸函數移動,查找和打印的正確路徑 -將遞歸函數賦值給python中的變量
一切工作正常。唯一的問題是,當我將該返回值賦給函數1中的變量並將其附加到二進制數組時,它將變爲None
。你能不能把遞歸的return語句分配給像這樣的變量?任何幫助將不勝感激,因爲我覺得我正在完成這一點的風口浪尖。
這裏是我的代碼:
def huffmanEncoder(s, t): """encodes string s with Tree t""" s = list(s) b = [] for i in range(len(s)): val = recursiveHuff(t, '', s[i]) print 'val:', val b.append(val) print b def recursiveHuff(tree, path, char): """given a tree, an empty string 'path', and a character, finds said char in tree and returns the binary path""" print 'looking for:\t', char, 'path:\t', path if not isLeaf(tree): recursiveHuff(getLeftChild(tree), path+'0', char) recursiveHuff(getRightChild(tree), path+'1', char) else: n = getNodeValue(tree) if n[1] == char: print 'found', char, 'at', path return path
OK - 所以最後2行recursiveHuff的'if'聲明應該是*回報* recursiveHuff(....)?做出改變後,算法只能進入3級深度,只有在碰到這三個級別時才能找到路徑... – wkd 2014-12-11 03:17:20
有關如何解決此問題的任何建議?我感到難過。 – wkd 2014-12-11 03:30:13
那麼,你需要找出哪個分支有你正在尋找的角色。如果它是左分支,則返回該路徑。如果它不在左邊,你必須向右邊探索。 (所以你不能立即返回左邊的路徑) – 2014-12-11 03:46:12