From 4437af52afc2289101c35027028cf5e9891df849 Mon Sep 17 00:00:00 2001 From: rihib Date: Sun, 1 Sep 2024 18:24:31 +0900 Subject: [PATCH 1/2] pullrequests/invert_binary_tree --- pullrequests/invert_binary_tree/step1.go | 23 +++++++++++++++++ pullrequests/invert_binary_tree/step2.go | 33 ++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 pullrequests/invert_binary_tree/step1.go create mode 100644 pullrequests/invert_binary_tree/step2.go 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 +} From 2ef461f9770746f0279814fe302af1fe8ef0b35a Mon Sep 17 00:00:00 2001 From: rihib Date: Mon, 23 Sep 2024 22:45:03 +0900 Subject: [PATCH 2/2] fix pullrequests/invert_binary_tree --- pullrequests/invert_binary_tree/step3.go | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 pullrequests/invert_binary_tree/step3.go 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 +}