给你两棵二叉树的根节点 p
和 q
,编写一个函数来检验这两棵树是否相同。
如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean key = true;
public void preOrder(TreeNode rootA, TreeNode rootB) {
if (rootA == null && rootB == null) {
return;
}else if(rootA != null && rootB != null){
}else{
key=false;
return;
}
if(rootA.val!=rootB.val){
key=false;
}
preOrder(rootA.left,rootB.left);
preOrder(rootA.right,rootB.right);
}
public boolean isSameTree(TreeNode p, TreeNode q) {
preOrder(p,q);
return key;
}
}