二叉树的前序遍历指:根->左子节点->右子节点,可以通过递归实现,也可以通过迭代实现。递归实现方法代码简单,复杂度高;迭代实现方法代码复杂,复杂度低。
Leetcode上python代码如下:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# digui
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
else:
return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right)
# diedai
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
stack_list = [root]
return_list = []
while(len(stack_list) != 0):
p = stack_list[-1]
stack_list = stack_list[:-1]
return_list.append(p.val)
if p.right:
stack_list.append(p.right)
if p.left:
stack_list.append(p.left)
return return_list