您的位置:首页 > 其它

leetcode 100 —— Same Tree

2015-08-08 16:25 330 查看
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);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: