100. Same Tree

题目描述(简单难度)

在这里插入图片描述
判断两个二叉树是否相同。

解法一

这道题就很简单了,只要把两个树同时遍历一下,遍历过程中判断数值是否相等或者同时为 null 即可。而遍历的方法,当然可以选择 DFS 里的先序遍历,中序遍历,后序遍历,或者 BFS。

当然实现的话,可以用递归,用栈,或者中序遍历提到的 Morris。

这里的话,由于最近几题对中序遍历用的多,所以就直接用中序遍历了。

class TreeNode{
	int val;
	TreeNode left;
	TreeNode right;
	TreeNode(int x){val=x;}
}

public class Same_Tree {
	
	public boolean isSameTree(TreeNode p,TreeNode q) {
		return inorderTraversal(p,q);
	}
	
	private boolean inorderTraversal(TreeNode p,TreeNode q) {
		if(p==null && q==null) {
			return true;
		}else if(p==null || q==null) {
			return false;
		}
		
		if(!inorderTraversal(p.left,q.left)) {
			return false;
		}
		
		if(p.val!=q.val) {
			return false;
		}
	
		if(!inorderTraversal(p.right,q.right)) {
			return false;
		}
		return true;
	}
}

时间复杂度:O(N)。对每个节点进行了访问。

空间复杂度:O(h),h 是树的高度,也就是压栈所耗费的空间。当然 h 最小为 log(N),最大就等于 N。

总结

这道题比较简单,本质上考察的就是二叉树的遍历。
在这里插入图片描述

参考文献

1.https://zhuanlan.zhihu.com/p/73111257

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
发出的红包

打赏作者

安替-AnTi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值