美文网首页
【Leetcode】【Python】中序遍历94. Binary

【Leetcode】【Python】中序遍历94. Binary

作者: 小歪与大白兔 | 来源:发表于2018-08-25 00:20 被阅读0次

实现二叉树的中序遍历

# 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]
        """
        # #递归方法
        if root == None:
            return []
        res = []
        res += self.inorderTraversal(root.left)
        res.append(root.val)
        res += self.inorderTraversal(root.right)
        return res

        #非递归的方法 借助栈的方式
        stack = []
        p = root
        res = []
        while p or stack:
            while p:
                stack.append(p)
                p = p.left
            p = stack.pop()
            res.append(p.val)
            p = p.right
        return res

相关文章

网友评论

      本文标题:【Leetcode】【Python】中序遍历94. Binary

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