算法:Same Tree

来源:互联网 发布:四川话发音软件 编辑:程序博客网 时间:2024/05/18 02:07
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 a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {    private:    bool isNodeEqual(TreeNode* n1, TreeNode* n2)    {        if(n1==NULL && n2==NULL)            return true;        if(n1==NULL || n2==NULL)            return false;                return (n1->val==n2->val) && isNodeEqual(n1->left, n2->left) && isNodeEqual(n1->right, n2->right);    }    public:    bool isSameTree(TreeNode* p, TreeNode* q) {        return isNodeEqual(p, q);    }};


0 0