1. 程式人生 > >百度面試題之二叉樹層次遍歷(從上到下,從下到上)

百度面試題之二叉樹層次遍歷(從上到下,從下到上)

1.二叉樹的層次遍歷 遞迴解法

class Node(object):
    def __init__(self, v, left=None, right=None):
        self.value = v
        self.left = left
        self.right = right

# 層次遍歷入口函式
def level_tranverse_iterate(node):
    if not node:
        return 0
    depth = Depth(node)
    print "depth:", depth
    for i in
range(1, depth+1): print_node_at_level(node, i) print # 計算樹高 def Depth(node): if not node: return 0 return max(Depth(node.left)+1,Depth(node.right)+1) # 當level=1時才輸出結點 def print_node_at_level(node, level): if not node or level < 1: return 0 if level == 1
: print node.value, return 0 print_node_at_level(node.left, level-1) print_node_at_level(node.right, level-1) node = Node(1, Node(3, Node(7, Node(0)), Node(6)), Node(2, Node(5), Node(4))) level_tranverse_iterate(node) # output: depth: 4 1 3 2 7 6 5 4 0

2.非遞迴解法

def level_tranverse_noniterate
(node):
stack = [node] while stack: node = stack.pop(0) print node.value if node.left: stack.append(node.left) if node.right: stack.append(node.right) node = Node(1, Node(3, Node(7, Node(0)), Node(6)), Node(2, Node(5), Node(4))) level_tranverse_noniterate(node) output: 1 3 2 7 6 5 4 0

3.從底向上的層次遍歷 非遞迴解法

就是將樹
1
3 2
7 6 5 4
0
列印為:
0   7 6 5 4    3 2     1

主要是要考慮每層的元素要分隔開,不然會亂。

# python 2.7
def from_bottom_to_top(node):
    if not node:
        return 0

    vect = [node]
    cur = 0
    last = 1

    while cur < len(vect):
        vect.append(None)   # 以None作為層之間的分隔
        last = len(vect)
        print "每層個數"+str(last-cur)
        # 每層的結點都判斷是否有左右子結點
        # 用cur來計數,cur==last-1即當前層的結點全部判斷完了
        #然後cur += 1,如果cur==len(vect),說明下一層沒有新結點加入,層次遍歷結束
        while cur < last - 1:
            if vect[cur].right:
                vect.append(vect[cur].right)
            if vect[cur].left:
                vect.append(vect[cur].left)
            cur += 1 
        cur+= 1

    # 按層輸出
    for i in range(len(vect)):
        if vect[i]:
            print vect[i].value,
        else:
            print