Same Tree:判断两棵二叉树是否相同

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;
        }
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值