二叉树的前序遍历:
递归:
# 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]
"""
ans = []
if root == None:
return ans
self.preTraverse(root, ans)
return ans
def preTraverse(self,t, ans):
ans.append(t.val)
if t.left:
self.preTraverse(t.left, ans)
if t.right:
self.preTraverse(t.right, ans)
非递归:
# 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]
"""
ans = []
stack = []
if root == None:
return ans
p = root
while(p or len(stack)):
if p:
ans.append(p.val)
stack.append(p)
p = p.left
else:
p = stack[-1]
stack.pop(-1)
p = p.right
return ans