二叉树(1)-----遍历

时间/空间复杂度分析

时间复杂度均为O(n);空间复杂度平均情况下为O(logn),最坏情况下为O(n).

Morris遍历:时间为O(n),空间为O(1)

一、前序遍历:

递归方式:

def preorder(tree):
    if tree:
        print(tree.val)
        preorder(tree.getLeftChild())
        preorder(tree.getRightChild())

非递归方式:时间复杂度O(n),空间复杂度O(n)

def preOrder(head):
    if not head:
        return None
    res ,stack = [] , [head]
    while stack:
        cur = stack.pop()
        res.append(cur.val)
        if cur.right:
            stack.append(cur.right)
        if cur.left:
            stack.append(cur.left)
    return res

二、中序遍历:

递归方式:

def inorder(tree):    
    if tree:
        inorder(tree.left)
        print(tree.val)
        inorder(tree.right)

非递归方式:

def InOrder(head):
    if not head:
        return None
    res ,stack = [] , []
    cur = head
    while stack or cur:
        if cur:
            stack.append(cur)
            cur = cur.left
        else:
            cur = stack.pop()
            res.append(cur.val)
            cur =cur.right
    return res

 三、后序遍历:

递归

def postorder(tree):
    if tree:
        postorder(tree.left)
        postorder(tree.right))
        print(tree.val)

非递归:

def PosOrder(head):
    if not head:
        return []
    s1 , s2 = [head] , []
    cur = head
    while s1:
        cur = s1.pop()
        s2.append(cur.val)
        if cur.left:
            s1.append(cur.left)
        if cur.right:
            s1.append(cur.right)
    return s2[::-1] 

 

class Node:
    def __init__(self,value):
        self.val = value
        self.left = None
        self.right = None
def posOrder(head):
    if not head:
        return []
    res = []
    cur = [head]
    while cur:
        node = cur[-1]
        if node.left and node.left != head and node.right!= head:
            cur.append(node.left)
        elif node.right and node.right != head:
            cur.append(node.right)
        else:
            res.append(cur.pop().val)
            head = node
    return res

if __name__ == '__main__':
    tree = Node(5)
    tree.left = Node(4)
    tree.right = Node(3)
    tree.left.left = Node(2)
    tree.left.right = Node(1)
    posOrder(tree)

四、层次遍历:

两个栈:

一个栈:

class Node:
    def __init__(self,value):
        self.val = value
        self.left = None
        self.right = None
def posOrder(root):
    if not root:
        return []
    last = root
    nlast = None
    stack = [root]
    res = [[]]
    while stack:
        head = stack.pop(0)
        res[-1].append(head.val)
        if head.left:
            stack.append(head.left)
            nlast = head.left
        if head.right:
            stack.append(head.right)
            nlast = head.right
        if head == last and stack:
            last = nlast
            res.append([])
    return res 

if __name__ == '__main__':
    tree = Node(5)
    tree.left = Node(4)
    tree.right = Node(3)
    tree.left.left = Node(2)
    tree.left.right = Node(1)
    posOrder(tree)

0个栈:(DFS)求每层的平均值

#####求每层的平均值   
 def averageOfLevels(self, root):
        """
        :type root: TreeNode
        :rtype: List[float]
        """
        def computeSum(root,height,sumlist,countlist):
            if not root:
                return 0
            if height>=len(countlist):
                countlist.append(0)
                sumlist.append(0)
            sumlist[height]+=root.val
            countlist[height]+=1.0
            computeSum(root.left,height+1,sumlist,countlist)
            computeSum(root.right,height+1,sumlist,countlist)
        sumlist=[]
        countlist=[]
        computeSum(root,0,sumlist,countlist)
        return [i/j if j!=0.0 else 0.0 for i,j in zip(sumlist,countlist)]
原文地址:https://www.cnblogs.com/Lee-yl/p/9809835.html