zoukankan      html  css  js  c++  java
  • 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)
    };
    

      

  • 相关阅读:
    bzoj2946 [Poi2000]公共串(SA,SAM)
    77 最长公共子序列
    C++ lower_bound 与 upper_bound 函数
    76 最长上升子序列
    75 寻找峰值
    C++标准输入问题
    74 第一个错误的代码版本
    73 前序遍历和中序遍历树构造二叉树
    72 中序遍历和后序遍历树构造二叉树
    71 二叉树的锯齿形层次遍历
  • 原文地址:https://www.cnblogs.com/JesseyWang/p/13098803.html
Copyright © 2011-2022 走看看