给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
示例 1:
输入:root = [1,null,2,3]
输出:[1,2,3]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
示例 4:
输入:root = [1,2]
输出:[1,2]
示例 5:
输入:root = [1,null,2]
输出:[1,2]
提示:
树中节点数目在范围 [0, 100] 内
-100 <= Node.val <= 100
进阶:递归算法很简单,你可以通过迭代算法完成吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal
参考:
- https://leetcode-cn.com/problems/binary-tree-preorder-traversal/solution/leetcodesuan-fa-xiu-lian-dong-hua-yan-shi-xbian-2/
- https://leetcode-cn.com/problems/binary-tree-preorder-traversal/solution/dai-ma-sui-xiang-lu-chi-tou-qian-zhong-hou-xu-de-d/
python
# 0144.二叉树前序遍历
# 递归 & 迭代
class Solution:
def preOrderRecur(self, head: TreeNode):
"""
递归遍历,NLR, 根左右
:param head:
:return:
"""
# 递归终止条件
def preOrder(head):
if head == None:
return
print(head.value + " ")
res.append(head.value)
preOrder(head.left)
preOrder(head.right)
res = []
preOrder(head)
return res
def preOrderIteration(self, head: TreeNode):
"""
迭代遍历, NLR
:param head:
:return:
"""
res = []
if head == None:
return res
stack = []
stack.append(head)
while stack:
node = stack.pop()
print(node.value + " ")
res.append(node.value)
if node.right != None:
stack.append(node.right) # 右节点先入栈后出栈
if node.left != None:
stack.append(node.left) # 左节点后入栈先出栈
return res
golang
package main
import "list"
type TreeNode struct {
Val int
Left, Right *TreeNode
}
func PreOrderRecur(root *TreeNode) []int {
res := []int{}
var preorder func(node *TreeNode)
preorder = fun(node *TreeNode) {
if node == nil {
return
}
res = append(res, node.Val)
preorder(node.Left)
preorder(node.Right)
}
preorder(root)
return vals
}
//迭代法前序遍历
/**
type Element struct {
// 元素保管的值
Value interface{}
// 内含隐藏或非导出字段
}
func (l *List) Back() *Element
前序遍历:中左右
压栈顺序:右左中
**/
func preorderTraversal(root *TreeNode) []int {
if root == nil {
return nil
}
var stack = list.New()
stack.PushBack(root.Right)
stack.PushBack(root.Left)
res:=[]int{}
res=append(res,root.Val)
for stack.Len()>0 {
e:=stack.Back()
stack.Remove(e)
node := e.Value.(*TreeNode)//e是Element类型,其值为e.Value.由于Value为接口,所以要断言
if node==nil{
continue
}
res=append(res,node.Val)
stack.PushBack(node.Right)
stack.PushBack(node.Left)
}
return res
}