100. Same Tree

本文介绍了一种检查两个二叉树是否一致的方法,通过递归和迭代两种方式实现,并对比了两者的优缺点。

题目描述:

给定两个二叉树,写一个函数来检查它们是否相同。

如果两棵树在结构上相同并且节点具有相同的值,则认为它们是相同的。

示例 1:

输入 :     1          1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

输出: true

示例 2:

输入  :    1          1
          /           \
         2             2

        [1,2],     [1,null,2]

输出: false

例 3:

输入 :     1          1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

输出: false

我的思路:

        直接判断p,q的值是否相等,然后递归判断p,q的left和right。或者可以层次遍历。

我的代码:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        if p and q:
            return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
        else:
            return p == q

Discuss:

def isSameTree2(self, p, q):
    stack = [(p, q)]
    while stack:
        node1, node2 = stack.pop()
        if not node1 and not node2:
            continue
        elif None in [node1, node2]:
            return False
        else:
            if node1.val != node2.val:
                return False
            stack.append((node1.right, node2.right))
            stack.append((node1.left, node2.left))
    return True

学到:

        多考虑下问题的多种解法,能不用递归就不用吧。

在R语言中,可以按照以下步骤加载`AmesHousing`包,设置相同超参数拟合随机森林袋装树模型,并比较它们的优劣。 首先,确保已经安装了所需的包,这里需要`AmesHousing`、`randomForest``ipred`包。 ```R # 安装并加载所需的包 if (!require(AmesHousing)) { install.packages("AmesHousing") library(AmesHousing) } if (!require(randomForest)) { install.packages("randomForest") library(randomForest) } if (!require(ipred)) { install.packages("ipred") library(ipred) } # 加载数据集 data("ames_raw") # 数据预处理 # 去除含有缺失值的行 ames_data <- na.omit(ames_raw) # 提取特征目标变量 X <- ames_data[, -which(names(ames_data) == "Sale_Price")] y <- ames_data$Sale_Price # 设置超参数 ntree <- 500 mtry <- ncol(X) # 对于袋装树,mtry等于特征数量 # 拟合随机森林模型 rf_model <- randomForest(x = X, y = y, ntree = ntree, mtry = mtry) # 拟合袋装树模型 bagging_model <- bagging(formula = Sale_Price ~ ., data = ames_data, nbagg = ntree) # 评估模型 # 划分训练集测试集 set.seed(123) train_index <- sample(1:nrow(ames_data), 0.7 * nrow(ames_data)) train_data <- ames_data[train_index, ] test_data <- ames_data[-train_index, ] # 重新拟合模型 rf_model_train <- randomForest(x = train_data[, -which(names(train_data) == "Sale_Price")], y = train_data$Sale_Price, ntree = ntree, mtry = mtry) bagging_model_train <- bagging(formula = Sale_Price ~ ., data = train_data, nbagg = ntree) # 在测试集上进行预测 rf_pred <- predict(rf_model_train, newdata = test_data) bagging_pred <- predict(bagging_model_train, newdata = test_data) # 计算均方误差(MSE) rf_mse <- mean((test_data$Sale_Price - rf_pred)^2) bagging_mse <- mean((test_data$Sale_Price - bagging_pred)^2) # 比较模型 if (rf_mse < bagging_mse) { print("随机森林模型表现更好") } else if (rf_mse > bagging_mse) { print("袋装树模型表现更好") } else { print("两个模型表现相同") } ``` 在上述代码中,首先加载了`AmesHousing`包并获取数据集,然后进行数据预处理,接着设置了相同的超参数(树的数量`ntree`)来拟合随机森林袋装树模型。之后划分训练集测试集,重新在训练集上拟合模型并在测试集上进行预测,最后通过计算均方误差(MSE)来比较两个模型的优劣。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值