猫史档案馆


【求助】【Golang】从中序与后序遍历序列构造二叉树

用户:留梦灵溪留梦灵溪查看:4 回复:3 评论:4 创建时间:2023-04-23T19:35:35


代码如下,有没有大佬能讲一下构造二叉树的思路是什么,想了一上午没想明白

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func buildTree(inorder []int, postorder []int) *TreeNode {
    if len(postorder) == 0 {
        return nil
    }
    root := &TreeNode{Val: postorder[len(postorder)-1]}
    stack := []*TreeNode{root}
    inorderIndex := len(inorder) - 1
    for i := len(postorder) - 2; i >= 0; i-- {
        postorderVal := postorder[i]
        node := stack[len(stack)-1]
        if node.Val != inorder[inorderIndex] {
            node.Right = &TreeNode{Val: postorderVal}
            stack = append(stack, node.Right)
        } else {
            for len(stack) > 0 && stack[len(stack)-1].Val == inorder[inorderIndex] {
                node = stack[len(stack)-1]
                stack = stack[:len(stack)-1]
                inorderIndex--
            }
            node.Left = &TreeNode{Val: postorderVal}
            stack = append(stack, node.Left)
        }
    }      
    return root
}


回复

上一页1 页 / 共 1下一页
留梦灵溪留梦灵溪

给的两个数组是 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,让构造并返回这颗 二叉树 。

 

点赞0


评论


𝙲ℴ𝗌𝔦𝒹ₑ𝑟𝙲ℴ𝗌𝔦𝒹ₑ𝑟

jvavspeic玩家不是看懂了一半又没有(主要是运算符不了解()

点赞0


评论


私塾­­私塾­­

高端的大佬,往往只需要最朴素的求助方式(bushi)

点赞0


评论