算法: 144. 二叉树前序遍历Binary Tree Preorder Traversal
Posted AI架构师易筋
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法: 144. 二叉树前序遍历Binary Tree Preorder Traversal相关的知识,希望对你有一定的参考价值。
144. Binary Tree Preorder Traversal
Given the root of a binary tree, return the preorder traversal of its nodes’ values.
Example 1:
Input: root = [1,null,2,3]
Output: [1,2,3]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Constraints:
- The number of nodes in the tree is in the range
[0, 100]
. -100 <= Node.val <= 100
Follow up: Recursive solution is trivial, could you do it iteratively?
1. 递归求解 – 计算机思维
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root: return []
res = [root.val]
res += self.preorderTraversal(root.left)
res += self.preorderTraversal(root.right)
return res
2. 遍历求解 – 人类思维
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
stack = [root]
while stack:
node = stack.pop()
if not node: continue
res.append(node.val)
stack.append(node.right)
stack.append(node.left)
return res
以上是关于算法: 144. 二叉树前序遍历Binary Tree Preorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode]144. Binary Tree Preorder Traversal二叉树前序遍历
[Leetcode 144]二叉树前序遍历Binary Tree Preorder Traversal
LeetCode 144. 二叉树的前序遍历 Binary Tree Postorder Traversal (Medium)