二叉树前中后遍历(统一写法)python solution

被网上各种写法恶心到了,下面是一个统一写法。
只要了解了先序遍历,中序和后序遍历都懂了。
这里面用到了栈,用栈不断压入根、左孩子,通过pop来回溯父节点,再访问右孩子。

  1. 先序遍历
"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: The root of binary tree.
    @return: Postorder in ArrayList which contains node values.
    """
    result = []
    def preorderTraversal(self, root):
        # write your code here
        if root is None:
            return []
        stack = []
        seq = [] #记录先序访问序列
        while ((root!=None) | (len(stack)!=0)):
            if root!=None:
                seq.append(root.val)   #先访问根节点
                stack.append(root)  
                root = root.left   
            else:
                root = stack.pop() #回溯至父节点
                root = root.right
        return seq     
  1. 中序遍历
"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: The root of binary tree.
    @return: Postorder in ArrayList which contains node values.
    """
    result = []
    def inorderTraversal(self, root):
        # write your code here
        if root is None:
            return []
        stack = []
        seq = []
        output = []
        while ((root!=None) | (len(stack)!=0)):
            if root!=None:
                stack.append(root)
                root = root.left
            else:
                root = stack.pop()
                seq.append(root.val) # 左孩子先pop出来,再pop根节点
                root = root.right
         
        return seq     
  1. 后序遍历
    先序:根左右
    后续:左右根

即把先序顺序中的 ‘根左右’转换为‘根右左’,然后反过来就变成了‘左右根’。

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: The root of binary tree.
    @return: Postorder in ArrayList which contains node values.
    """
    result = []
    def postorderTraversal(self, root):
        # write your code here
        if root is None:
            return []
        stack = []
        seq = []
        output = []
        while ((root!=None) | (len(stack)!=0)):
            if root!=None:
                seq.append(root.val)
                stack.append(root)
                root = root.right  # 这从left变成了 right
            else:
                root = stack.pop()
                root = root.left # 这从right变成了 left
                
        while seq:  # 后序遍历 是 将先序遍历的反过来
            output.append(seq.pop())

        return output                    
    原文作者:fighting41love
    原文地址: https://www.jianshu.com/p/7cbb17fe525c
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞