美文网首页
二叉树的遍历【递归、非递归】以及自己的感受

二叉树的遍历【递归、非递归】以及自己的感受

作者: 而立之年的技术控 | 来源:发表于2019-12-24 17:28 被阅读0次

    --------又来了一次二叉树的遍历,每次都有不一样的理解!真不知道那些大佬是如何想出这些牛逼的算法的,佩服至极!!!!大家多写,多想,对这些的理解真的会发生变化!!!
    ~~~~~~~~
    --------这里多说一句哈,就是大家一定要多写多想!有很多知识是学的时候怎么都理解不了,过段时间回来在看,直接就明白了,连自己都懵了!融会贯通不就如此嘛!!!!我的学习方法就是四个字:反反复复!!!!


    微信图片_20191224172703.jpg
    class TreeNode:
        def __init__(self, val):
            self.val = val
            self.left = None
            self.right = None
    
    
    # 先序  【递归】
    def pre_order(root):
        if not root:
            return None
        print(root.val)
        pre_order(root.left)
        pre_order(root.right)
    
    
    # 中序  【递归】
    def mid_order(root):
        if not root:
            return None
        mid_order(root.left)
        print(root.val)
        mid_order(root.right)
    
    
    # 后序  【递归】
    def last_order(root):
        if not root:
            return None
        last_order(root.left)
        last_order(root.right)
        print(root.val)
    
    
    # 先序  【循环】
    def pre(root):
        if not root:
            return None
        stack = []
        tmp = root
        while stack or tmp:
            while tmp:
                print(tmp.val)
                stack.append(tmp)
                tmp = tmp.left
            node = stack.pop()
            tmp = node.right
    
    
    # 中序  【循环】
    def mid(root):
        if not root:
            return None
        stack = []
        tmp = root
        while stack or tmp:
            while tmp:
                stack.append(tmp)
                tmp = tmp.left
            node = stack.pop()
            print(node.val)
            tmp = node.right
    
    
    # 后序  【循环】
    def last(root):
        if not root:
            return None
        stack = []
        tmp = root
        while stack or tmp:
            while tmp:
                stack.append(tmp)
                tmp = tmp.left
            node = stack[-1]
            tmp = node.right
            if tmp is None:
                node = stack.pop()
                print(node.val)
                while stack and node == stack[-1].right:
                    node = stack.pop()
                    print(node.val)
    
    
    if __name__ == '__main__':
        node1 = TreeNode(1)
        node2 = TreeNode(2)
        node3 = TreeNode(3)
        node4 = TreeNode(4)
        node5 = TreeNode(5)
        node6 = TreeNode(6)
        node7 = TreeNode(7)
    
        node1.left = node2
        node1.right = node3
        node2.left = node4
        node2.right = node5
        node3.left = node6
        node3.right = node7
    
        # pre_order(node1)
        # mid_order(node1)
        # last_order(node1)
        # pre(node1)
        # mid(node1)
        last(node1)
    

    相关文章

      网友评论

          本文标题:二叉树的遍历【递归、非递归】以及自己的感受

          本文链接:https://www.haomeiwen.com/subject/eyefoctx.html