题解 | #实现二叉树先序,中序和后序遍历# go + 迭代

实现二叉树先序,中序和后序遍历

http://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362

go + 迭代

package main
import . "nc_tools"
/*
 * type TreeNode struct {
 *   Val int
 *   Left *TreeNode
 *   Right *TreeNode
 * }
 */

/**
 * 
 * @param root TreeNode类 the root of binary tree
 * @return int整型二维数组
*/
func threeOrders( root *TreeNode ) [][]int {
    // write code here
    if root == nil {
        return nil
    }

    ret := make([][]int, 0)
    ret = append(ret, pre(root), middle(root), suff(root))

    return ret
}


func pre(root *TreeNode) []int {
    r := make([]int, 0)

    stack := []*TreeNode{root}

    for len(stack) > 0 {
        top := stack[len(stack)-1]
        if top != nil {
            stack = stack[:len(stack)-1]

            if top.Right != nil {
                stack = append(stack, top.Right)
            }
            if top.Left != nil {
                stack =append(stack, top.Left)
            }
            stack = append(stack, top, (*TreeNode)(nil))
        }else{
            node := stack[len(stack)-2]
            r = append(r, node.Val)
            stack = stack[:len(stack)-2]
        }
    }

    return r
}


func middle(root *TreeNode) []int {
    r := make([]int, 0)

    stack := []*TreeNode{root}

    for len(stack) > 0 {
        top := stack[len(stack)-1]
        if top != nil {
            stack = stack[:len(stack)-1]

            if top.Right != nil {
                stack = append(stack, top.Right)
            }
            stack = append(stack, top, (*TreeNode)(nil))
            if top.Left != nil {
                stack =append(stack, top.Left)
            }
        }else{
            node := stack[len(stack)-2]
            r = append(r, node.Val)
            stack = stack[:len(stack)-2]
        }
    }

    return r
}

func suff(root *TreeNode) []int{
    r := make([]int, 0)

    stack := []*TreeNode{root}

    for len(stack) > 0 {
        top := stack[len(stack)-1]
        if top != nil {
            stack = stack[:len(stack)-1]
            stack = append(stack, top, (*TreeNode)(nil))

            if top.Right != nil {
                stack = append(stack, top.Right)
            }
            if top.Left != nil {
                stack =append(stack, top.Left)
            }
        }else{
            node := stack[len(stack)-2]
            r = append(r, node.Val)
            stack = stack[:len(stack)-2]
        }
    }

    return r
}
全部评论

相关推荐

Cassifa:发的字比你都多的一律视为骗子或者想白嫖压榨实习生的
点赞 评论 收藏
分享
02-15 17:05
已编辑
东华理工大学 前端工程师
Beeee0927:我建议是精简一点吧,比如主修的课程,技能特长,自我评价我是觉得可以删掉了。然后项目经历可能要考虑怎么改得更真实一点,因为就我看起来感觉里面太多的东西像是在实际项目中才能接触到的
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
正在热议
更多
牛客网
牛客企业服务