Last active
July 24, 2023 20:29
-
-
Save maxclav/6e7f7222bb5ede3be4503babd1ba5259 to your computer and use it in GitHub Desktop.
Invert Binary Tree in Go (GoLang).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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