//本文内容来自StarSight,欢迎访问。
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) {
boolean l=false,r=false;
if(p==null){
if(q==null)
return true;
else if(q!=null)
return false;
}
if(q==null){
return false;
}
if(p.left!=null)
l = isSameTree(p.left,q.left);
else if(q.left==null)
l = true;
if(p.right!=null)
r = isSameTree(p.right,q.right);
else if(q.right==null)
r = true;
if(p.val==q.val&&l==true&&r==true)
return true;
return false;
}
}
依次遍历,没啥好说的。