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
思路一:树的先序+中序结果可已确定一颗数的结构,对两棵树分别记录下先序+中序结果并比较,若完全相同则为同一棵树。
注意[1 , 1] 与 [ 1 , null , 1],先序+中序结果完全相同,所以要在遍历时区分左子树还是有子树。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public void predfs(TreeNode n,List<String> l,String local){
if(n==null) return;
l.add(n.val+local);
predfs(n.left,l,"left");
predfs(n.right,l,"right");
}
public void middfs(TreeNode n,List<String> l,String local){
if(n==null) return;
predfs(n.left,l,"left");
l.add(n.val+local);
predfs(n.right,l,"right");
}
public boolean isSameTree(TreeNode p, TreeNode q) {
ArrayList<String> pp =new ArrayList<String>();
ArrayList<String> pm =new ArrayList<String>();
ArrayList<String> qp =new ArrayList<String>();
ArrayList<String> qm =new ArrayList<String>();
predfs(p,pp,"");
predfs(q,qp,"");
middfs(p,pm,"");
middfs(q,qm,"");
if(pp.size()!=qp.size()||pm.size()!=qm.size()) return false;
for(int i =0;i<pp.size();i++){
if( !pp.get(i).equals(qp.get(i)) ) return false;
}
for(int i =0;i<pm.size();i++){
if( !pm.get(i).equals(qm.get(i)) ) return false;
}
return true;
}
}
思路二:不依靠树,递归比较每个节点,即若一方为空另一方非空,或者两方节点不同,则返回FALSE。
/**
* 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;
if(p==null||q==null) return false;
if(p.val==q.val){
return isSameTree(p.left, q.left)&&isSameTree(p.right, q.right);
}else{
return false;
}
}
}