Skip to content

Instantly share code, notes, and snippets.

@maxclav
Last active July 24, 2023 20:29
Show Gist options
  • Save maxclav/6e7f7222bb5ede3be4503babd1ba5259 to your computer and use it in GitHub Desktop.
Save maxclav/6e7f7222bb5ede3be4503babd1ba5259 to your computer and use it in GitHub Desktop.
Invert Binary Tree in Go (GoLang).
package binarytree
// Tree is a binary tree.
type Tree struct {
Root *Node
}
// Invert reverses the binary tree.
func Invert(tree *Tree) {
_ = InvertFromNode(tree.Root)
}
// Node is a binary tree node.
type Node struct {
Val int
Left *Node
Right *Node
}
// InvertFromNode reverses the children of a sub binary tree from node:
// - children on the left become children on the right
// - children on the right become children on the left
func InvertFromNode(node *Node) *Node {
if node != nil {
node.Left, node.Right = InvertFromNode(node.Right), InvertFromNode(node.Left)
}
return node
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment