问题描述
Given two binary trees, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical and the nodes have the same value. Example : 地址
问题分析
递归(类似前序遍历) 类似前序遍历非递归形式(可以用两个栈,也可以用一个栈,一次弹出来两个 ) 层序遍历(可以用两个队列,也可以用一个队列,一次出队两个进行比较 )
代码实现
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(p.right, q.right);
}
public boolean isSameTree (TreeNode p, TreeNode q) {
if (p == null && q == null ) {
return true ;
}
if (p == null || q == null ) {
return false ;
}
LinkedList<TreeNode> pQueue = new LinkedList<>();
LinkedList<TreeNode> qQueue = new LinkedList<>();
pQueue.add(p);
qQueue.add(q);
while (! pQueue.isEmpty() && ! qQueue.isEmpty()) {
TreeNode pNode = pQueue.remove();
TreeNode qNode = qQueue.remove();
if (pNode == null && qNode == null ) {
continue ;
}
if (pNode == null || qNode == null || pNode.val != qNode.val) {
return false ;
}
pQueue.add(pNode.left);
pQueue.add(pNode.right);
qQueue.add(qNode.left);
qQueue.add(qNode.right);
}
return pQueue.size() == qQueue.size();
}