卖萌的弱渣

I am stupid, I am hungry.

Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes' values.

Example

Given:

1
2
3
4
5
    1
   / \
  2   3
 / \
4   5

return [1,2,4,5,3].

Solution

(Binary-Tree-Preorder-Traversal.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""


class Solution:
    """
    @param root: The root of binary tree.
    @return: Preorder in ArrayList which contains node values.
    """
    def preorder(self, node, result):
        result.append(node.val)
        if node.left != None:
            self.preorder(node.left,result)
        if node.right != None:
            self.preorder(node.right,result)
        return result

    def preorderTraversal(self, root):
        # write your code here
        result = []
        if root == None:
            return result
        self.preorder(root,result)
        return result