1)递归
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}
if (p == null || q == null) {
return false;
}
return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(q.right, p.right);
}
2)迭代(注:用其它容器也可以,按顺序比较节点就OK)
public boolean isSameTree(TreeNode p, TreeNode q) {
Stack<TreeNode> stackP = new Stack<>();
Stack<TreeNode> stackQ = new Stack<>();
stackP.push(p);
stackQ.push(q);
TreeNode currentP, currentQ;
while ((!stackP.empty()) && (!stackQ.empty())) {
currentP = stackP.pop();
currentQ = stackQ.pop();
if (currentP == null && currentQ == null) {
continue;
}
if (currentP == null || currentQ == null) {
return false;
}
if (currentP.val != currentQ.val) {
return false;
}
stackP.push(currentP.left);
stackP.push(currentP.right);
stackQ.push(currentQ.left);
stackQ.push(currentQ.right);
}
return true;
}