Golang前序遍历+后序遍历(N叉树)中序遍历(二叉树) 统一规范化写法 迭代法

前序遍历:

采用stack(先进后出),从子节点反序灌入

/**
 * Definition for a Node.
 * type Node struct {
 *     Val int
 *     Children []*Node
 * }
 */

func preorder(root *Node) []int {

    stack := make([]*Node, 0)
    res := make([]int, 0)
    if root == nil{
        return res
    }
    stack = append(stack, root)
    for len(stack)!=0{
        curr := stack[len(stack)-1]
        stack = stack[:len(stack)-1]
        res = append(res, curr.Val)
        childList := curr.Children
        for i:=len(childList)-1; i>=0; i--{
            stack = append(stack, childList[i])
        }
    }
    return res
}

后序遍历

采用stack,子节点正序灌入,最后把所有结果进行倒序输出

/**
 * Definition for a Node.
 * type Node struct {
 *     Val int
 *     Children []*Node
 * }
 */

func postorder(root *Node) []int {
    stack := make([]*Node, 0)
    res := make([]int, 0)
    if root == nil{
        return res
    }
    stack = append(stack, root)
    for len(stack)>0{
        curr := stack[len(stack)-1]
        stack = stack[:len(stack)-1]
        res = append(res, curr.Val)
        childList := curr.Children
        for i:=0; i<len(childList); i++{
            stack = append(stack, childList[i])
        }
    }
    for i,j:=0,len(res)-1; i<j; i, j = i+1,j-1{
        res[i], res[j] = res[j], res[i]
    }
    return res
    
}

中序遍历

先把左边的开到底,没了再加入当前节点,循环条件为curr!=nil || len(stack)>0

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func inorderTraversal(root *TreeNode) []int {
    stack := make([]*TreeNode, 0)
    res := make([]int, 0)
    for root !=nil || len(stack)>0{
        for root != nil{
            stack = append(stack, root)
            root = root.Left
        }
        root = stack[len(stack)-1]
        stack = stack[:len(stack)-1]
        res = append(res, root.Val)
        root = root.Right
    }
    return res

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值