【LEETCODE OJ】Binary Tree Preorder Traversal

时间:2022-10-12 22:33:02

Problem Link:

http://oj.leetcode.com/problems/binary-tree-preorder-traversal/

Even iterative solution is easy, just use a stack storing the nodes not visited. Each iteration, pop a node and visited it, then push its right child and then left child into stack if possible.

Note the special case that the root is NULL.

The python code is as follows, which is accepted by OJ.leetcode.

# 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):
"""
Iterative way using a stack, hope no LTE...
"""
res = []
non_visited = []
if root is not None:
non_visited.append(root)
while non_visited:
top = non_visited.pop()
res.append(top.val)
if top.right:
non_visited.append(top.right)
if top.left:
non_visited.append(top.left)
return res