• 100.相同的树


    题目描述: 给定两个二叉树,编写一个函数来检验它们是否相同。
    如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

    • 深度优先遍历,递归或者用栈
    //C
    //递归
    bool isSameTree(struct TreeNode* p, struct TreeNode* q){
        if(p == NULL && q == NULL) return true;
        else if(p == NULL || q == NULL) return false;
        else if(p -> val == q -> val){
            return isSameTree(p -> left,q -> left) && isSameTree(p -> right, q -> right);
        }
        return false;
    }
    
    //用栈
    #define MAXNODE 5000
    bool isSameTree(struct TreeNode* p, struct TreeNode* q){
        int bottom = 0, top = 0;
        struct TreeNode **S = (struct TreeNode **)malloc(sizeof(struct TreeNode *) * MAXNODE);
    
        S[top++] = p;
        S[top++] = q;
        struct TreeNode* p_temp;
        struct TreeNode* q_temp;
        while(bottom != top){
            p_temp = S[bottom++];
            q_temp = S[bottom++];
                
            if(p_temp == NULL && q_temp == NULL) continue;
            else if(p_temp != NULL && q_temp == NULL) return false;
            else if(p_temp == NULL && q_temp != NULL) return false;
            else if(p_temp -> val != q_temp -> val) return false;
            else {
                S[top++] = q_temp -> right;
                S[top++] = p_temp -> right;
                S[top++] = q_temp -> left;
                S[top++] = p_temp -> left;
            }        
        }
        return true;    
    }
    • 把两棵树序列化成字符串进行比较
    //JS
    
    //法一:本质也是递归
    var isSameTree = function(p, q) {
        let sequntial = function(root){
            if(!root) return '#';
            return `${root.val}!${sequntial(root.left)}${sequntial(root.right)}`;
        }
        return sequntial(p) == sequntial(q);
    };
    
    //法二:使用JSON.stringify
    var isSameTree = function(p, q) {
    return JSON.stringify(p)===JSON.stringify(q)
    };
    

      

  • 相关阅读:
    为Jboss4配置数据库
    从JAVA源代码到EXE可执行文件
    连接数据库出现:Connections could not be acquired from the underlying database
    SVN修改用户名与密码
    linux 下开放指定端口
    Nginx 禁止IP访问及未绑定的域名跳转
    Proguard混淆后无法正常运行的问题:
    How To Automate Internet Explorer to POST Form Data
    poj 2667 hotel 线段树
    poj 3691 DNA repair AC自动机+DP
  • 原文地址:https://www.cnblogs.com/JesseyWang/p/13098803.html
Copyright © 2020-2023  润新知