/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ classSolution{ publicbooleanisSameTree(TreeNode p, TreeNode q){ if (p == null && q == null) { returntrue; } if (p == null || q == null) { returnfalse; } if (p.val != q.val) { returnfalse; } return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); } }
解决方案4(Golang)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ funcisSameTree(p *TreeNode, q *TreeNode)bool { if p == nil || q == nil { return p == q } return p.Val == q.Val && isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right) }