leetcode刷题。总结,记录,备忘 100
2015-05-23 22:13
281 查看
leetcode 100题是判断2个二叉树是否相同
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.
这个题目同样使用深度优先搜索,利用递归,首先判断当前节点值是否相同,再判断每个当前节点的左右子树是否相同,如果3个条件都相同才返回真。递归结束条件是2棵树都遍历到了最远的叶节点,返回真,或者其中一个已到最远叶节点,另一个并没有,就返回假。
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.
这个题目同样使用深度优先搜索,利用递归,首先判断当前节点值是否相同,再判断每个当前节点的左右子树是否相同,如果3个条件都相同才返回真。递归结束条件是2棵树都遍历到了最远的叶节点,返回真,或者其中一个已到最远叶节点,另一个并没有,就返回假。
bool isSameTree(struct TreeNode* p, struct TreeNode* q) { if (p == NULL && q == NULL) return true; else if (p == NULL || q == NULL) return false; bool flagV; if (p->val == q->val) flagV = true; else flagV = false; bool flagL = isSameTree(p->left, q->left); bool flagR = isSameTree(p->right, q->right); if (flagL && flagR && flagV) return true; else return false; }
相关文章推荐
- leetcode刷题,总结,记录,备忘 309
- leetcode刷题,总结,记录,备忘 223
- leetcode刷题,总结,记录,备忘 90
- leetcode刷题,总结,记录,备忘 287
- leetcode刷题,总结,记录,备忘 129
- leetcode刷题,总结,记录,备忘 268
- leetcode刷题,总结,记录,备忘, 279
- leetcode刷题,总结,记录 ,备忘 172
- leetcode刷题,总结,记录,备忘 108
- leetcode刷题,总结,记录,备忘331
- leetcode刷题,总结,记录,备忘 112
- leetcode刷题,总结,记录,备忘 263
- leetcode刷题, 总结,记录, 备忘 230
- leetcode刷题, 总结,记录,备忘22
- leetcode刷题 总结 记录 备忘 64
- leetcode刷题,总结, 记录,备忘 12
- leetcode刷题,总结,记录,备忘89
- leetcode刷题,总结,记录,备忘 36
- leetcode刷题。总结,记录,备忘 104
- leetcode刷题,总结,记录,备忘 284