LeetCode探索之旅(21)-100判断两棵树是否相同

今天继续刷LeetCode,第21题,判断两棵树是否相等。

分析:
采用递归的方式,通过中序遍历,遍历到二叉树的所有节点,包括叶子节点。然后判断两棵树中对应位置的值是否相等,不相等就返回false,知道所有节点值都相等,就返回true。

问题:
1、考虑树为空的情况;
2、递归调用的写法;

附上代码:

/**
 * 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;
        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);
            else
                return false;
        }
    }
};

猜你喜欢

转载自blog.csdn.net/JerryZengZ/article/details/87966539
今日推荐