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]
        """
        rst = []
        rst = self.helper(rst, root)
        return rst
    
    def helper(self, rst, root):
        if root is None:
            return rst
        
        rst.append(root.val)
        rst = self.helper(rst, root.left)
        rst = self.helper(rst, root.right)
        return rst
  1. remember to add self before each method and variable

  2. Divide and conquer is all u need.

class Solution(object):
    def preorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        rst = []
        stack = []
        if root:   # we checked inside the loop for not appending None in the stack, but dont forget checking it at the begining.
            stack.append(root)
        else:
            return rst
        while(stack):
            top = stack.pop()
            rst.append(top.val)
            if top.right:
                stack.append(top.right)
            if top.left:
                stack.append(top.left)
        return rst
  1. When solving it in iterative way with stack, remember to append nodes in inverse order, appending later node (right) first (before left).

  2. we checked not appending None in the stack inside the loop, but don't forget also checking it at the beginning.

Last updated