题目描述
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 1:
Input: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
Output: true
Example 2:
Input: 1 1
/ \
2 2
[1,2], [1,null,2]
Output: false
Example 3:
Input: 1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
Output: false
思路分析
先序遍历,依次比较节点值即可
二叉树类的题,要注意递归方法的使用
循环写法:层序遍历 利用队列,依次比较两树中每个节点值
代码
方法一:递归
public 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;
}
结果
方法二:循环写法
public boolean isSameTree(TreeNode p, TreeNode q) {
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(p);
queue.offer(q);
while ( !queue.isEmpty() ){
TreeNode temp1 = queue.poll();
TreeNode temp2 = queue.poll();
if (temp1==null && temp2==null) {
continue;
}
if (temp1==null || temp2==null || temp1.val != temp2.val) {
return false;
}
queue.offer(temp1.left);
queue.offer(temp2.left);
queue.offer(temp1.right);
queue.offer(temp2.right);
}
return true;
}
结果