package main
import (
"fmt"
//"encoding/json"
)
type Node struct {
Value int
Left *Node
Right *Node
}
func GetRows(node *Node, count int) [][]int {
out := make([][]int, count)
Rows(node, 0, out)
return out
}
// Rows adds all of the binary node values into a 2D array representing
// the row level and the row values.
func Rows(node *Node, level int, out [][]int) {
if node == nil {
return
}
out[level] = append(out[level], node.Value)
// checking for nil here could save some time instead of making
// another function call that isn't needed...
Rows(node.Left, level+1, out)
Rows(node.Right, level+1, out)
}
// TestResult checks each resulting row against the expected row values.
func TestResults(expected, actual [][]int) error {
elen := len(expected)
alen := len(actual)
if alen != elen {
return fmt.Errorf("Expected %d rows, got %d", elen, alen)
}
for i := 0; i < elen; i++ {
if len(expected[i]) != len(actual[i]) {
return fmt.Errorf("Expected %d values at row %d, got %d", len(expected[i]), len(actual[i]))
}
for j := 0; j < len(expected[i]); j++ {
if expected[i][j] != actual[i][j] {
return fmt.Errorf("Expected %d at %d,%d, got %d", expected[i][j], i, j, actual[i][j])
}
}
}
fmt.Println("PASS!")
return nil
}
func main() {
root := Node{Value: 5}
root.Left = &Node{Value: 3}
root.Left.Left = &Node{Value: 1}
root.Left.Right = &Node{Value: 4}
root.Right = &Node{Value: 7}
root.Right.Left = &Node{Value: 6}
root.Right.Right = &Node{Value: 9}
root.Right.Right.Left = &Node{Value: 8}
expected := [][]int{
{5},
{3, 7},
{1, 4, 6, 9},
{8},
}
actual := GetRows(&root, 4)
fmt.Printf("%v\n\n", actual)
if e := TestResults(expected, actual); e != nil {
fmt.Println(e)
}
}