leetcode 100 —— Same Tree

来源:互联网 发布:软件测试方法分类 编辑:程序博客网 时间:2024/06/16 12:42


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.



思路:先序遍历,可以设置flag,提前返回。


class Solution {bool flag = true;public:bool isSameTree(TreeNode* p, TreeNode* q) {preOrder(p, q);return flag;}void preOrder(TreeNode* p, TreeNode *q){if (!flag||(!p&&!q)) return;if ((!p&&q) || (p&&!q) || (p->val != q->val)){flag = false;return;}preOrder(p->left, q->left);preOrder(p->right, q->right);}};


0 0
原创粉丝点击