LeetCode Online Judge 题目C# 练习 - Same Tree

Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

 1         public static bool SameTree(BTNode p, BTNode q)

 2         {

 3             if (p == null && q == null)

 4                 return true;

 5             if ((p == null && q != null) || (p != null && q == null))

 6                 return false;

 7             if (p.Value != q.Value)

 8                 return false;

 9 

10             return SameTree(p.Left, q.Left) && SameTree(p.Right, q.Right);

11         }

代码分析:

  现在LEETCODE的Online Judge开始加入一些树的题目了。碰到树的题目,第一时间想到的就是递归了。不过容易忘记了几个判定的case, p, q都是 null, return ture, 其中一个是null 一个不是, return false。

你可能感兴趣的:(LeetCode)