diff --git a/pullrequests/invert_binary_tree/step1.go b/pullrequests/invert_binary_tree/step1.go new file mode 100644 index 0000000..baae19d --- /dev/null +++ b/pullrequests/invert_binary_tree/step1.go @@ -0,0 +1,23 @@ +//lint:file-ignore U1000 Ignore all unused code +package invertbinarytree + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +/* +時間:3分30秒 + +再帰的に左右のノードを入れ替えていけば良いというのにはすぐに気づき、すんなり実装することができた。 +*/ +func invertTreeStep1(root *TreeNode) *TreeNode { + if root == nil { + return nil + } + invertTreeStep1(root.Left) + invertTreeStep1(root.Right) + root.Left, root.Right = root.Right, root.Left + return root +} diff --git a/pullrequests/invert_binary_tree/step2.go b/pullrequests/invert_binary_tree/step2.go new file mode 100644 index 0000000..8b4171c --- /dev/null +++ b/pullrequests/invert_binary_tree/step2.go @@ -0,0 +1,33 @@ +//lint:file-ignore U1000 Ignore all unused code +package invertbinarytree + +/* +Step1は冗長だったのでリファクタした。 +これぐらい短いと早期リターンしなくても良いかなと思い下記のようにしました。 +またイテレーティブに解く方法も実装しました。 +*/ +func invertTreeStep2(root *TreeNode) *TreeNode { + if root != nil { + root.Left, root.Right = invertTreeStep2(root.Right), invertTreeStep2(root.Left) + } + return root +} + +func invertTreeIterative(root *TreeNode) *TreeNode { + if root == nil { + return nil + } + stack := []*TreeNode{root} + for len(stack) > 0 { + node := stack[len(stack)-1] + stack = stack[:len(stack)-1] + node.Left, node.Right = node.Right, node.Left + if node.Left != nil { + stack = append(stack, node.Left) + } + if node.Right != nil { + stack = append(stack, node.Right) + } + } + return root +} diff --git a/pullrequests/invert_binary_tree/step3.go b/pullrequests/invert_binary_tree/step3.go new file mode 100644 index 0000000..e5d894e --- /dev/null +++ b/pullrequests/invert_binary_tree/step3.go @@ -0,0 +1,10 @@ +//lint:file-ignore U1000 Ignore all unused code +package invertbinarytree + +func invertTreeRecursive(root *TreeNode) *TreeNode { + if root == nil { + return nil + } + root.Left, root.Right = invertTreeRecursive(root.Right), invertTreeRecursive(root.Left) + return root +}