题目描述:
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
中文理解:判断给定的两棵树是不是同一颗数。
解题思路:按照层次遍历的方法将树的遍历结果保存起来,然后依次比较每个节点的节点值和左右子树是否存在的情况是否相同。在判断左右子树是否存在情况一致时可以采用设置两个整数计数值,初始值为0,若存在左子树则加1,存在右子树时加2,两个计算值相同则左右子树的存在情况一致。
代码(java):
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
//使用层次遍历的方法把每个节点装入动态数组里面
if(p==null && q==null)return true;
else if(p==null || q==null)return false;
ArrayList<TreeNode> tree1=new ArrayList<TreeNode>();
ArrayList<TreeNode> tree2=new ArrayList<TreeNode>();
Queue<TreeNode> queue=new LinkedList<TreeNode>();
queue.offer(p);
while(queue.peek()!=null){
TreeNode top=queue.poll();
tree1.add(top);
if(top.left!=null){
queue.offer(top.left);
}
if(top.right!=null){
queue.offer(top.right);
}
}
queue.offer(q);
while(queue.peek()!=null){
TreeNode top=queue.poll();
tree2.add(top);
if(top.left!=null){
queue.offer(top.left);
}
if(top.right!=null){
queue.offer(top.right);
}
}
if(tree1.size()!=tree2.size())return false;
else{
for(int i=0;i<tree1.size();i++){
//判断每个节点值、以及左右子节点存在情况是否相同是否相同
if(tree1.get(i).val==tree2.get(i).val){
int tree1Count=0;
int tree2Count=0;
if(tree1.get(i).left==null)tree1Count+=1;
if(tree1.get(i).right==null)tree1Count+=2;
if(tree2.get(i).left==null)tree2Count+=1;
if(tree2.get(i).right==null)tree2Count+=2;
if(tree1Count!=tree2Count){
return false;
}
}
else{
return false;
}
}
}
return true;
}
}