100. Same Tree

博客围绕判断两棵二叉树是否相同展开。题目要求判断两棵二叉树结构是否相同且节点值相等。给出两种方法思路,分别是递归法(recursive)和迭代法(iterative)。

题目描述

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.
在这里插入图片描述在这里插入图片描述在这里插入图片描述

方法思路

Appraoch1:recursive

class Solution {
    //Runtime: 2 ms, faster than 100.00% 
    //Memory Usage: 36.8 MB, less than 73.43%
    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 false;
        return isSameTree(p.left, q.left)&&isSameTree(p.right, q.right);
    }
}

Appraoch2:iterative

class Solution {
    //Runtime: 2 ms, faster than 100.00%
    //Memory Usage: 37 MB, less than 5.52% 
  public boolean check(TreeNode p, TreeNode q) {
    // p and q are null
    if (p == null && q == null) return true;
    // one of p and q is null
    if (q == null || p == null) return false;
    if (p.val != q.val) return false;
    return true;
  }

  public boolean isSameTree(TreeNode p, TreeNode q) {
    if (p == null && q == null) return true;
    if (!check(p, q)) return false;

    // init deques
    ArrayDeque<TreeNode> deqP = new ArrayDeque<TreeNode>();
    ArrayDeque<TreeNode> deqQ = new ArrayDeque<TreeNode>();
    deqP.addLast(p);
    deqQ.addLast(q);

    while (!deqP.isEmpty()) {
      p = deqP.removeFirst();
      q = deqQ.removeFirst();

      if (!check(p, q)) return false;
      if (p != null) {
        // in Java nulls are not allowed in Deque
        if (!check(p.left, q.left)) return false;
        if (p.left != null) {
          deqP.addLast(p.left);
          deqQ.addLast(q.left);
        }
        if (!check(p.right, q.right)) return false;
        if (p.right != null) {
          deqP.addLast(p.right);
          deqQ.addLast(q.right);
        }
      }
    }
    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)来比较两个模型的优劣。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值