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)
};

  

 

posted @ 2020-06-12 13:13  Jessey45  阅读(187)  评论(0编辑  收藏  举报