给定两棵二叉树,检查它们是否是相同的二叉树
package cn.lspj.ch1.base;
public class CheckSameTree {
public static boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null) return true;
if(p == null || q == null) return false;
if(p.val == q.val)
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
return false;
}
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public static void main(String[] args) {
TreeNode pRoot = new TreeNode(1);
TreeNode pLeft = new TreeNode(2);
TreeNode pRight = new TreeNode(3);
pRoot.left = pLeft;
pRoot.right = pRight;
TreeNode qRoot = new TreeNode(1);
TreeNode qLeft = new TreeNode(2);
TreeNode qRight = new TreeNode(3);
qRoot.left = qLeft;
qRoot.right = qRight;
System.out.println(isSameTree(pRoot,qRoot));
}
}
往
期
回
顾