144. Binary Tree Preorder Traversal

# 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 preorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        #use the LIFO feature of stack,
        #if the node is not empty, output the value,  then first put right node into stack, then put left node into stack
        #next loop will read the left node first, after finish interating the left node, it will pop the right node and iterate the right node. 
        res=[]
        stack=[root]
        while stack:
            node=stack.pop()
            if node:
                res.append(node.val)
                stack.append(node.right)
                stack.append(node.left)
                
        return res

你可能感兴趣的:(144. Binary Tree Preorder Traversal)