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 @ 2023-05-15 16:18  小星code  阅读(8)  评论(0)    收藏  举报