您的位置:首页 > 其它

【LEETCODE OJ】Binary Tree Preorder Traversal

2014-04-04 02:03 330 查看
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


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: