Approach: Use preorder traversal.
public bool AreSame(BinaryTree tree)
{
return this.IsSameTree(this.Root, tree.Root);
}
private bool IsSameTree(BinaryTreeNode p, BinaryTreeNode q)
{
if (p == null)
{
return q == null;
}
else if (q == null)
{
return false;
}
return p.Value == q.Value && this.IsSameTree(p.LeftNode, q.LeftNode) && this.IsSameTree(p.RightNode, q.RightNode);
}
No comments:
Post a Comment