🥈Medium
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
题解
递归
递归还是挺好写的,只要记住先序顺序为root->left->right
即可
Python
# 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: TreeNode) -> List[int]:
def preorder(node):
if not node:
return
res.append(node.val)
preorder(node.left)
preorder(node.right)
res = []
preorder(root)
return res
一行解决
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right)
JavaScript
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal = function(root) {
const res = []
const preOrder = (root) => {
if (root == null) return
res.push(root.val)
preOrder(root.left)
preOrder(root.right)
};
preOrder(root)
return res
};
复杂度分析
- 时间复杂度:
其中n是二叉树节点数,每个节点恰好被遍历一次
- 空间复杂度:
为递归过程中的开销。平均情况下为
,最坏情况下树为链状,为
迭代
迭代过程如图所示Python
```pythonDefinition 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: TreeNode) -> List[int]:res=[] if not root: return res stack = [root] while(stack): cur=stack.pop() res.append(cur.val) if cur.right: stack.append(cur.right) if cur.left: stack.append(cur.left) return res
<a name="l4jHb"></a>
#### JavaScript
```javascript
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
const preorderTraversal = (root) => {
if (root === null){
return []
}
let ans=[]
let stack=[root]
while(stack.length>0){
let node = stack.pop()
ans.push(node.val)
if(node.right){
stack.push(node.right)
}
if(node.left){
stack.push(node.left)
}
}
return ans
}
复杂度分析
- 时间复杂度:
其中n是二叉树节点数,每个节点恰好被遍历一次
- 空间复杂度:
为迭代过程中显式栈的开销。平均情况下为
,最坏情况下树为链状,为