diff --git a/src/chapter4/binary_tree_node.go b/src/chapter4/binary_tree_node.go new file mode 100644 index 0000000..9751ad8 --- /dev/null +++ b/src/chapter4/binary_tree_node.go @@ -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 +} diff --git a/src/chapter4/problem6.go b/src/chapter4/problem6.go new file mode 100644 index 0000000..44c1f8b --- /dev/null +++ b/src/chapter4/problem6.go @@ -0,0 +1,26 @@ +package chapter4 + +// Successor checks the next node in binary tree with in-order traversal +func Successor(node *BTNode) *BTNode { + if node == nil { + return nil + } + + // node has right child + if node.Right != nil { + for n := node.Right; ; n = n.Left { + if n.Left == nil { + return n + } + } + } + + // node is right child of Parent + for ; node.Parent != nil; node = node.Parent { + if node.Parent.Left == node { + return node.Parent + } + } + + return nil +} diff --git a/src/chapter4/problem6_test.go b/src/chapter4/problem6_test.go new file mode 100644 index 0000000..e139dd8 --- /dev/null +++ b/src/chapter4/problem6_test.go @@ -0,0 +1,88 @@ +package chapter4 + +import ( + "reflect" + "testing" +) + +func TestSuccessor(t *testing.T) { + // Initiate Node for parent traversal + n1 := &BTNode{} + n2 := &BTNode{} + n3 := &BTNode{} + n2.SetRight(n1) + n3.SetLeft(n2) + + n4 := &BTNode{} + n5 := &BTNode{} + n6 := &BTNode{} + n5.SetRight(n4) + n6.SetRight(n5) + + tests := map[string]struct { + in *BTNode + out *BTNode + }{ + + "Should return nil if input is nil": { + in: nil, + out: nil, + }, + + "Should return nil if input doesn't have parent and children": { + in: &BTNode{}, + out: nil, + }, + + "Should return most left node of right subtree": { + in: &BTNode{ + Right: &BTNode{ + Left: &BTNode{ + Value: 5, + Left: &BTNode{ + Value: 10, + Right: &BTNode{}, + }, + }, + }, + }, + out: &BTNode{ + Value: 10, + Right: &BTNode{}, + }, + }, + + /* + * n3 + * / + * n2 + * \ + * n1 + */ + "Should return parent which has left child": { + in: n1, + out: n3, + }, + + /* + * n6 + * \ + * n5 + * \ + * n4 + */ + "Should return nil whne input is the last node to traversal": { + in: n4, + out: nil, + }, + } + + for k, test := range tests { + t.Run(k, func(t *testing.T) { + out := Successor(test.in) + if !reflect.DeepEqual(out, test.out) { + t.Errorf("actual=%+v expected=%+v", out, test.out) + } + }) + } +}