Question: https://oj.leetcode.com/problems/binary-tree-preorder-traversal/
Question Name: Binary Tree Preorder Traversal
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a list of integers def preorderTraversal(self, root): # Empty tree if root == None: return [] result = [] stack = [root] while len(stack) != 0: # Access the root firstly current = stack.pop() result.append(current.val) # Then we are going to access its left son and right son. if current.right != None: stack.append(current.right) if current.left != None: stack.append(current.left) return result |