leetcode二叉树中序遍历

在这里插入图片描述
不管是前中后序遍历,有个非常简单的办法就是递归,先来用递归:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution(object):
    def inorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        l=[]
        def add(root):
            if root==None:
                return 
            add(root.left)
            l.append(root.val)
            add(root.right)
        add(root)
        return l

按照题目说的迭代来:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        l1=[]
        l2=[]
        p=root
        while l2 or p:
            while p:
                l2.append(p)
                p=p.left  #左子树
            p=l2.pop()
            l1.append(p.val)
            p=p.right   #开始判断右子树
        return l1
发布了29 篇原创文章 · 获赞 28 · 访问量 283

猜你喜欢

转载自blog.csdn.net/weixin_45398265/article/details/105038720