66. 二叉树的前序遍历
中文English
给出一棵二叉树,返回其节点值的前序遍历。
样例
样例 1:
输入:{1,2,3}
输出:[1,2,3]
解释:
1
/
2 3
它将被序列化为{1,2,3}
前序遍历
样例 2:
输入:{1,#,2,3}
输出:[1,2,3]
解释:
1
2
/
3
它将被序列化为{1,#,2,3}
前序遍历
挑战
你能使用非递归实现么?
注意事项
- 首个数据为根节点,后面接着是其左儿子和右儿子节点值,"#"表示不存在该子节点。
- 节点数量不超过20
输入测试数据 (每行一个参数)如何理解测试数据?
分治法:
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: A Tree @return: Preorder in ArrayList which contains node values. """ def preorderTraversal(self, root): # write your code here if not root: return [] results = [] left = self.preorderTraversal(root.left) right = self.preorderTraversal(root.right) results.append(root.val) results.extend(left) results.extend(right) return results
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: A Tree @return: Preorder in ArrayList which contains node values. """ def preorderTraversal(self, root): # write your code here return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right) if root else []
非递归版本:
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: A Tree @return: Preorder in ArrayList which contains node values. """ def preorderTraversal(self, root): # write your code here #非递归 results = [] stack = [root] while stack: pop_node = stack.pop(0) results.append(pop_node.val) if pop_node.left: stack.append(pop_node.left) if pop_node.right: stack.append(pop_node.right) return results