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

Add problem 4 of chapter 4 #6

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/chapter4/binary_tree_node.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package chapter4

// BTNode represents a node in binary tree
type BTNode struct {
Value int
Parent *BTNode
Left *BTNode
Right *BTNode
}

// SetRight sets child on right side
func (n *BTNode) SetRight(c *BTNode) {
n.Right = c
c.Parent = n
}

// SetLeft sets child on right side
func (n *BTNode) SetLeft(c *BTNode) {
n.Left = c
c.Parent = n
}
34 changes: 34 additions & 0 deletions src/chapter4/problem4.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package chapter4

import "math"

// CheckBalanced checks if given tree is balanced
func CheckBalanced(root *BTNode) bool {
return CheckBalancedR(root) != math.MinInt64
}

// CheckBalancedR checks if given tree is balanced by checking depth
// It returns math.MinInt64 if it's not balanced
func CheckBalancedR(node *BTNode) int64 {
if node == nil {
return -1
}

leftD := CheckBalancedR(node.Left)
if leftD == math.MinInt64 {
return math.MinInt64
}

rightD := CheckBalancedR(node.Right)
if rightD == math.MinInt64 {
return math.MinInt64
}

if diff := leftD - rightD; diff < -1 || diff > 1 {
return math.MinInt64
}
if rightD < leftD {
return leftD + 1
}
return rightD + 1
}
53 changes: 53 additions & 0 deletions src/chapter4/problem4_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package chapter4

import "testing"

func TestCheckBalanced(t *testing.T) {
tests := map[string]struct {
in *BTNode
out bool
}{

"Should return true when tree only has a single node": {
in: &BTNode{},
out: true,
},

"Should return true when difference of height of subtree is less than or equal to 1": {
in: &BTNode{
Right: &BTNode{
Right: &BTNode{},
},
Left: &BTNode{},
},
out: true,
},

"Should return false when difference of height of subtree is greater than 1": {
in: &BTNode{
Right: &BTNode{
Right: &BTNode{
Right: &BTNode{},
Left: &BTNode{},
},
},
Left: &BTNode{},
},
out: false,
},

"Should return true when tree is nil": {
in: nil,
out: true,
},
}

for k, test := range tests {
t.Run(k, func(t *testing.T) {
out := CheckBalanced(test.in)
if out != test.out {
t.Errorf("actual=%t expected=%t", out, test.out)
}
})
}
}