算法题---二叉树的前中后遍历

package main

import "fmt"

/*
分别按照二叉树先序,中序和后序打印所有的节点。
输入
{1,2,3}
输出
[[1,2,3],[2,1,3],[2,3,1]]

*/

type TreeNode struct {
    Val int
    Left *TreeNode
    Right *TreeNode
}

var pres, ins, posts []int

func threeOrders(root *TreeNode) [][]int {
    res := make([][]int, 3)
    res[0] = preOrder(root)
    res[1] = midOrder(root)
    res[2] = postOrder(root)
    return res
}


func preOrder(root *TreeNode) []int{
    arr := make([]int, 0)
    if root == nil{
        return arr
    }
    arr = append(arr, root.Val)
    arr = append(arr, preOrder(root.Left)...)
    arr = append(arr, preOrder(root.Right)...)
    return arr
}

func midOrder(root *TreeNode) []int{
    arr := make([]int, 0)
    if root == nil{
        return arr
    }
    arr = append(arr, midOrder(root.Left)...)
    arr = append(arr, root.Val)
    arr = append(arr, midOrder(root.Right)...)
    return arr
}

func postOrder(root *TreeNode) []int{
    arr := make([]int, 0)
    if root == nil{
        return arr
    }
    arr = append(arr, postOrder(root.Left)...)
    arr = append(arr, postOrder(root.Right)...)
    arr = append(arr, root.Val)
    return arr
}

func preOrderTraversal( root *TreeNode ) []int{
    arr := make([]int, 0)
    if root == nil {
        return arr
    }
    stack := make([]*TreeNode, 0)
    for len(stack) > 0 || root != nil{
        for root != nil{
            arr = append(arr, root.Val)
            stack = append(stack, root)
            root = root.Left
        }
        root = stack[len(stack) - 1].Right
        stack = stack[:len(stack) - 1]
    }
    return arr
}

func midOrderTraversal( root *TreeNode ) []int{
    arr := make([]int, 0)
    if root == nil {
        return arr
    }
    stack := make([]*TreeNode, 0)
    for len(stack) > 0 || root != nil{
        for root != nil{
            stack = append(stack, root)
            root = root.Left
        }
        root = stack[len(stack) - 1]
        arr = append(arr, root.Val)
        root = root.Right
        stack = stack[:len(stack) - 1]
    }
    return arr
}

func postOrderTraversal( root *TreeNode ) []int{
    arr := make([]int, 0)
    if root == nil {
        return arr
    }
    stack := make([]*TreeNode, 0)
    var lastNode *TreeNode
    for len(stack) > 0 || root != nil{
        for root != nil{
            stack = append(stack, root)
            root = root.Left
        }
        root = stack[len(stack) - 1]
        stack = stack[:len(stack) - 1]
        if root.Right == nil || lastNode == root.Right {
            arr = append(arr, root.Val)
            lastNode = root
            root = nil
        }else{
            stack = append(stack, root)
            root = root.Right
        }
    }
    return arr
}

func main(){
    a := new(TreeNode)
    a.Val = 1

    b := new(TreeNode)
    b.Val = 2

    c := new(TreeNode)
    c.Val = 3

    a.Left = b
    a.Right = c

    res := threeOrders(a)
    fmt.Println(res)
}
原文地址:https://www.cnblogs.com/syw-home/p/14661109.html