From 53af4bd234097b9521899fe82fe9b375bdcdc5f2 Mon Sep 17 00:00:00 2001 From: openset Date: Thu, 21 Feb 2019 09:59:12 +0800 Subject: [PATCH] Add: Same Tree --- problems/same-tree/same_tree.go | 19 ++++++++++++++ problems/same-tree/same_tree_test.go | 38 ++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/problems/same-tree/same_tree.go b/problems/same-tree/same_tree.go index 5aa1952d3..5d7469eb5 100644 --- a/problems/same-tree/same_tree.go +++ b/problems/same-tree/same_tree.go @@ -1 +1,20 @@ package same_tree + +import . "github.com/openset/leetcode/internal/kit" + +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func isSameTree(p *TreeNode, q *TreeNode) bool { + if p == nil { + return q == nil + } else if q == nil || p.Val != q.Val { + return false + } + return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right) +} diff --git a/problems/same-tree/same_tree_test.go b/problems/same-tree/same_tree_test.go index 5aa1952d3..6d3e8c681 100644 --- a/problems/same-tree/same_tree_test.go +++ b/problems/same-tree/same_tree_test.go @@ -1 +1,39 @@ package same_tree + +import ( + "testing" + + . "github.com/openset/leetcode/internal/kit" +) + +type caseType struct { + p []int + q []int + expected bool +} + +func TestIsSameTree(t *testing.T) { + tests := [...]caseType{ + { + p: []int{1, 2, 3}, + q: []int{1, 2, 3}, + expected: true, + }, + { + p: []int{1, 2}, + q: []int{1, NULL, 2}, + expected: false, + }, + { + p: []int{1, 2, 1}, + q: []int{1, 1, 2}, + expected: false, + }, + } + for _, tc := range tests { + output := isSameTree(SliceInt2TreeNode(tc.p), SliceInt2TreeNode(tc.q)) + if output != tc.expected { + t.Fatalf("input: %v %v, output: %v, expected: %v", tc.p, tc.q, output, tc.expected) + } + } +}