`
836811384
  • 浏览: 549150 次
文章分类
社区版块
存档分类
最新评论

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

 
阅读更多

原题:

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

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

若您觉得该文章对您有帮助,请在下面用鼠标轻轻按一下“顶”,哈哈~~·

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics