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.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) return true; //所有节点对比完
else if (p == null || q == null) return false;//(子)节点数量不等
if (p.val != q.val) return false;// (子)节点值不等
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); // 检验下一级节点
}
}
以上代码出自http://blog.csdn.net/xudli/article/details/8557010, 本文旨在总结一下思路
判断树一个树节点是否相等三个条件: 是否有左节点, 是否有右节点, 值是否相等.