【leetCode】Same Tree

来源:互联网 发布:java开发项目实例 编辑:程序博客网 时间:2024/06/08 15:24

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 {public:    bool isSameTree(TreeNode* p, TreeNode* q) {        //如果p和q中有一个空一个非空        if((!p && q) || (p && !q))        {            return false;        }        //如果p和q都是空树的话,也是相等的        else if(p==NULL && q== NULL)        {            return true;        }        //先判断结点值相等否,不等就直接返回false,没必要判断子树是否相等了        if(p->val != q->val)            return false;        else        {            //如果结点值相等,就递归到子树中去,看左右子树是否相等            bool right = isSameTree(p->right,q->right);            bool left = isSameTree(p->left,q->left);                        if(right && left)                return true;            else                return false;        }        return false;    }};

结果:


话说这个0ms也是醉了

0 0
原创粉丝点击