[LeetCode] [C] 100. Same Tree

来源:互联网 发布:sql去除重复数据 编辑:程序博客网 时间:2024/06/06 06:58

To solve the problem about Binary Tree,

I still used Recursive Method.


Here, I still wrote another function to help traverse.

And I still declared the variable outside the two functions.


Simply speaking,

The program traversed these two trees synchronously,

and compared the value of every two tree nodes.


The Runtime of the program is 3 ms.

The length of the code is 476 Bytes.


bool is;void isSame (struct TreeNode* p, struct TreeNode* q) {    if (!p && !q) return;    else if ((!p && q) || (p && !q)) {        is=false;        return;    }    if (p->val!=q->val) {        is=false;        return;    } else {        if (p->left || q->left) isSame (p->left, q->left);        if (p->right || q->right) isSame (p->right, q->right);    }}bool isSameTree(struct TreeNode* p, struct TreeNode* q) {    is=true;    isSame(p,q);    return is;}

Of course, there are better methods solving this problem.

More than half of people only used 0~1 ms.



原创粉丝点击