100. Same Tree

判断两课树是否是相等的树,提示tags有两种:tree和bfs。那联想到递归和BFS算法了。
题目描述:
Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

给出两棵二叉树,写一个函数判断它们是否相等。两棵二叉树在结构相等的时候还要判断节点的值是否相等。

1.递归:

bool isSameTree(TreeNode* p, TreeNode* q) {
        if(p == NULL && q == NULL){return true; }
        if(p == NULL && q != NULL){return false;}
        if(p != NULL && q == NULL){return false;}
        else{
            if(p->val != q->val){
                return false;
            }
            else{
                return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
            } 
        }  
   }

分析下几种情况:
1.p和q都为NULL时返回true
2.p和q一个为NULL而另外一个不为NULL,在结构上就不等,返回false
3.除此之外,就是都存在左右节点,那就应该比较它们的val了,如果不等,就可以直接返回false;如果相等,继续判断它们的左右节点,递归下去
最后的答案必须是左右子树都相等,才返回true,&&上它们

注:其实真正的返回值是p==NULL&&q==NULL返回的true,因为两棵树相等的话,一路递归下去,都没有返回false,直到最后的p==NULL&&q==NULL,这时的p和q代表最深的叶子节点

python代码:

class Solution(object):
    def isSameTree(self, p, q):
        if p == None and q == None:
            return True
        if p is not None and q is None:
            return False
        if p is None and q is not None:
            return False
        else:
            if p.val != q.val:
                return False
            else:
                return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)   

注:python中使用and表示&&,or表示||。

2.BFS

广度优先遍历

这里的思路是:
1.构造两个队列了l1和l2,用这两个队列同步搜索树的所有节点并进队,每一次进队看树的这个位置有几个节点,有左右就先进左再进右,只有一个就进那一个(bfs能把所有的节点都扫描到并且进队列)
2.之后是比较队头元素,先将队头元素拷贝一份,直接直接删除,如果拷贝的队头元素的val不相等,直接返回false;否则继续下一次循环,可见下一次循环又是新的队头元素

这样比较下去直到两棵树都空了,还没有返回false,说明两个树是完全相等的,返回true

很明显看的出来这是树的层次遍历,从上到下,从左到右,也就是广度

class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
       if(p == NULL && q == NULL){return true;}
       if((p == NULL && q != NULL) || (p != NULL && q == NULL)){return false;}

       queue<TreeNode*> l1;
       queue<TreeNode*> l2;
       l1.push(p);  //只是压了个头部进去,根节点
       l2.push(q);
       TreeNode* node1 = p;
       TreeNode* node2 = q;
       while(!l1.empty() && !l2.empty()){

           node1 = l1.front();
           l1.pop();
           node2 = l2.front();
           l2.pop();

           if(node1->val != node2->val){
               return false;
           }
           if(node1->left != NULL && node2->left != NULL){
               l1.push(node1->left);
               l2.push(node2->left);  //node1,2指针偏移
           }

           if(node1->right != NULL && node2->right != NULL){
               l1.push(node1->right);
               l2.push(node2->right);  //node1,2指针偏移
           }

           //如果树的结构不同,那直接返回false
           if(node1->left == NULL && node2->left != NULL ||node1->left != NULL && node2->left == NULL){
               return false;
           }
           if(node1->right == NULL && node2->right != NULL || node1->right != NULL && node2->right == NULL){
               return false;
           }  
       }  
       return true;  
    }
};
R R version 4.2.2 (2022-10-31) -- "Innocent and Trusting" Copyright (C) 2022 The R Foundation for Statistical Computing Platform: x86_64-conda-linux-gnu (64-bit) R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under certain conditions. Type 'license()' or 'licence()' for distribution details. Natural language support but running in an English locale R is a collaborative project with many contributors.Type 'contributors()' for more information and 'citation()' on how to cite R or R packages in publications. Type 'demo()' for some demos, 'help()' for on-line help, or 'help.start()' for an HTML browser interface to help. Type 'q()' to quit R. library(ape) setwd("/ifs1/User/dengwei/NTF_data/7.14/rooted_species_tree") species_tree <- read.tree("species_tree.treefile")> compare_trees <- function(gene_tree_file, species_tree) { gene_tree <- read.tree(gene_tree_file) diff_count <- comparePhylo(gene_tree, species_tree, force.rooted = TRUE) return(diff_count) } batch_compare_trees <- function(gene_tree_folder, species_tree) { gene_tree_files <- list.files(path = gene_tree_folder, pattern = ".treefile", full.names = TRUE) diff_counts <- data.frame(Gene_Tree_File = gene_tree_files, Diff_Count = numeric(length(gene_tree_files)), stringsAsFactors = FALSE) for (i in seq_along(gene_tree_files)) { gene_tree_file <- gene_tree_files[i] diff_counts$Diff_Count[i] <- compare_trees(gene_tree_file, species_tree) } return(diff_counts) } gene_tree_folder <- "/ifs1/User/dengwei/NTF_data/7.14/rooted_gene_tree" diff_counts <- batch_compare_trees(gene_tree_folder, species_tree) Error in if (n1 == n2) paste("Both trees have the same number of tips:", : the condition has length > 1
最新发布
07-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值