首页 > 代码库 > Same Tree

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) {
        int flag = 1;/*标识两棵树是否一样*/
        _isSameTree_core(p, q, flag);
        return flag;
    }
    void _isSameTree_core(TreeNode *p, TreeNode *q, int &flag) {
        if (!p && !q)
            return;
        else if ((!p && q) || (p && !q) || (p->val != q->val)) {
            flag = 0;
            return;
        } else if (p && q) {
            _isSameTree_core(p->left, q->left, flag);
            _isSameTree_core(p->right, q->right, flag);
        }
    }
};