Same Tree

来源:互联网 发布:服装画册拍摄淘宝拍摄 编辑:程序博客网 时间:2024/06/06 13:19

原题:
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.

解题:
递归判断每个位置的节点在树中的位置是否一致,再进一步判断对应的值是否相等。可以AC的C++代码如下:

    bool isSameTree(TreeNode* p, TreeNode* q) {        if((!p && q) || (p && !q))            return false;        else if(!p && !q)            return true;        if(p->val != q->val)            return false;        else{            return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);        }    }
0 0
原创粉丝点击