Skip to content

Latest commit

 

History

History
58 lines (52 loc) · 1.3 KB

094.md

File metadata and controls

58 lines (52 loc) · 1.3 KB

94. Binary Tree Inorder Traversal

Solution 1

# 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]
        """
        ans = []
        stack = []
        p = root
        while p or stack:
            if p:
                stack.append(p)
                p = p.left
            else:
                p = stack.pop()
                ans.append(p.val)
                p = p.right
        return ans

Solution 2

# 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]
        """
        ans = []
        if not root:
            return ans
        if root.left:
            ans.extend(self.inorderTraversal(root.left))
        ans.append(root.val)
        if root.right:
            ans.extend(self.inorderTraversal(root.right))
        return ans