您的位置:首页 > 其它

Same Tree--比较两个二叉树是否相同

2013-10-27 11:07 399 查看
原题:

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.

=> 两个二叉树相同,当且仅当他们的结构相同,且节点的值也相同。



/**
 * Definition for binary tree
 * 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) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
         }
};


晓东分析:

其实两个二叉树是否相同的判断,看起来还是蛮简单的,若用递归实现的话,就是要左,右节点作为根节点的二叉树是都是相同的,且val也要是相同的即可。

只是需要考虑几个特殊情况,比如左右节点一个是null一个不是这样的情况。



代码实现:

/**
 * Definition for binary tree
 * 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) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(p == NULL && q == NULL) return true;
        if(!(p != NULL && q != NULL)) return false;
        bool left_result = isSameTree(p->left, q->left);
        bool right_result = isSameTree(p->right, q->right);
        bool value_result = p->val == q->val;
        return (left_result == true && right_result == true && value_result == true)? true: false;
        }
};


执行结果:



52 / 52test cases passed.
Status:

Accepted

Runtime: 16 ms
希望大家有更好的算法能够提出来,不甚感谢。



若您觉得该文章对您有帮助,请在下面用鼠标轻轻按一下“顶”,哈哈~~·
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: