LeetCode 144. 二叉树的前序遍历

题目链接:LeetCode 144. 二叉树的前序遍历

题意:

给你二叉树的根节点 root ,返回它节点值的 前序 遍历。

解题思路:

对于二叉树的遍历,有递归和非递归两种遍历方式,
1. 递归遍历
根据“左->根->右”的顺序,直接模拟即可。注意按照递归三部曲(递归的参数和返回值、递归的终止条件、单层递归的逻辑)

递归代码如下:

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
var res []int
func preorderTraversal(root *TreeNode) []int {

    res = []int{}
    pt(root)
    return res
}
func pt(root *TreeNode){
    if root == nil{
        return
    }
    res = append(res,root.Val)
    pt(root.Left)
    pt(root.Right)
}
  1. 迭代遍历

迭代代码如下

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func preorderTraversal(root *TreeNode) []int {
    var res []int //结果数组
    var stk []*TreeNode  //栈
    for root != nil || len(stk)!= 0{ 
        for root != nil { //如果当前节点不空,
            res = append(res,root.Val) //遍历当前节点
            stk = append(stk,root) //入栈
            root = root.Left  //遍历左子树
        }
        root = stk[len(stk)-1]  //取出栈顶元素
        stk = stk[:len(stk)-1]  //出栈
        root = root.Right  //遍历右子树
    }
    return res
}

posted @   小星code  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示