标签:二叉树
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 a binary tree node.
* 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(!isSameNode(p, q))
return false;
if(p==null)return true;
return isSameTree(p.left,q.left)&& isSameTree(p.right,q.right);
}
private boolean isSameNode(TreeNode p, TreeNode q) {
// TODO Auto-generated method stub
if(p==null&&q==null)
return true;
if(p!=null&&q!=null&&p.val==q.val)
return true;
return false;
}
}
标签:二叉树
原文地址:http://blog.csdn.net/tule_ant/article/details/45485153