100. Same Tree (DFS)

来源:互联网 发布:湖北广电网络客服电话 编辑:程序博客网 时间:2024/06/09 15:52

1. Description

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.


2. Analysis

这样的比较无疑是要逐一对比的,所以每一个节点都会遍历到。可以适当做出一些小技巧来判断特殊情况,减少不必要的运算,比如,在遍历前判断根节点的情况等。本算法设计的思路很简单,就是逐层从左到右比较。


3. Algorithm achievement

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    bool 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;        queue<TreeNode*> T1, T2;        T1.push(p);        T2.push(q);        TreeNode * tmp1 = NULL, *tmp2 = NULL;        while(!T1.empty() && !T2.empty()) {            if(T1.size() != T2.size()) return false;            for(int i = 0, n = T1.size(); i < n; i++) {                tmp1 = T1.front();                tmp2 = T2.front();                T1.pop();                T2.pop();                if(tmp1->val != tmp2->val) return false;                if((tmp1->left != NULL && tmp2->left == NULL)                     || (tmp1->left == NULL && tmp2->left != NULL)) {                        return false;                    }                if((tmp1->right != NULL && tmp2->right == NULL)                     || (tmp1->right == NULL && tmp2->right != NULL)) {                        return false;                    }                if(tmp1->left != NULL && tmp2->left != NULL) {                    T1.push(tmp1->left);                    T2.push(tmp2->left);                }                if(tmp1->right != NULL && tmp2->right != NULL) {                    T1.push(tmp1->right);                    T2.push(tmp2->right);                }                       }        }        return true;    } };

4. 复杂度分析

意料之中,耗时相对其他解法还存在改进的空间。(待优化)

这里写图片描述
改进:
注意:不要使用尾递归。

class Solution {public:    bool 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;        if (isSameTree(p->left, q->left) && isSameTree(p->right, q->right))            return true;        return false;    } };