Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

一下截图为证,相同代码,go判题第一次判题正确,接着第二次就是运行错误。如此反复循环 #23

Open
moutainMan opened this issue Aug 5, 2023 · 3 comments

Comments

@moutainMan
Copy link
Contributor

image

{5DUO(T4@W~~%9K(` N@2%N

@moutainMan
Copy link
Contributor Author

代码如下:

package main

import "fmt"

// 定义二叉树结构体
type treeNode struct {
    val   byte      // 节点的值
    left  *treeNode // 左子树
    right *treeNode // 右子树
}

// 先序遍历和中序遍历构建二叉树
func buildTree(preorder, inorder []byte) *treeNode {
    if len(preorder) == 0 {
        return nil
    }

    // 先序遍历的第一个节点是根节点
    root := &treeNode{
        val: preorder[0],
    }

    // 找到根节点在中序遍历序列中的位置
    i := 0
    for ; i < len(inorder); i++ {
        if inorder[i] == root.val {
            break
        }
    }

    // 递归构建左右子树
    root.left = buildTree(preorder[1:1+i], inorder[:i])
    root.right = buildTree(preorder[1+i:], inorder[i+1:])

    return root
}

// 计算二叉树的高度(深度)
func height(root *treeNode) int {
    if root == nil {
        return 0
    }

    leftHeight := height(root.left)
    rightHeight := height(root.right)

    if leftHeight > rightHeight {
        return leftHeight + 1
    } else {
        return rightHeight + 1
    }
}

func main() {
    var k int
    for {
        _, err := fmt.Scan(&k)
        if err != nil {
            break
        }

        preorder := make([]byte, k)
        inorder := make([]byte, k)

        fmt.Scan(&preorder, &inorder)

        // 构建二叉树
        root := buildTree(preorder, inorder)

        // 计算二叉树高度
        fmt.Println(height(root))
    }
}

@youngyangyang04
Copy link
Owner

重复代码不要重复提交,系统判断是重复代码后,会直接随机返回结果,不会判题了

@moutainMan
Copy link
Contributor Author

OK

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants