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语言代码有问题 #2910

Open
lizzy-0323 opened this issue Mar 6, 2025 · 0 comments
Open

二叉树构建的go语言代码有问题 #2910

lizzy-0323 opened this issue Mar 6, 2025 · 0 comments

Comments

@lizzy-0323
Copy link

源代码:

func constructBinaryTree(array []int) *TreeNode {
    var root *TreeNode
    nodes := make([]*TreeNode, len(array))

    // 初始化二叉树节点
    for i := 0; i < len(nodes); i++ {
	var node *TreeNode
	if array[i] != -1 {
	    node = &TreeNode{Val: array[i]}
	}
	nodes[i] = node
	if i == 0 {
	    root = node
	}
    }
    // 串联节点
    for i := 0; i*2+2 < len(array); i++ {
        if nodes[i] != nil {
	    nodes[i].Left = nodes[i*2+1]
	    nodes[i].Right = nodes[i*2+2]
	}
    }
    return root
}

这里最后串联节点的部分感觉不对,这样的话会漏掉节点,感觉可以写成

	for i := 0; i < len(arr); i++ {
		if i*2+1 < len(arr) {
			nodes[i].Left = nodes[i*2+1]
		}
		if i*2+2 < len(arr) {
			nodes[i].Right = nodes[i*2+2]
		}
	}
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

1 participant