【leetCode】Same Tree
来源:互联网 发布:java开发项目实例 编辑:程序博客网 时间:2024/06/08 15:24
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.
需要注意的是,空树也是相等的。
翠花上代码:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: bool isSameTree(TreeNode* p, TreeNode* q) { //如果p和q中有一个空一个非空 if((!p && q) || (p && !q)) { return false; } //如果p和q都是空树的话,也是相等的 else if(p==NULL && q== NULL) { return true; } //先判断结点值相等否,不等就直接返回false,没必要判断子树是否相等了 if(p->val != q->val) return false; else { //如果结点值相等,就递归到子树中去,看左右子树是否相等 bool right = isSameTree(p->right,q->right); bool left = isSameTree(p->left,q->left); if(right && left) return true; else return false; } return false; }};
结果:
话说这个0ms也是醉了
0 0
- Leetcode - Tree - Same Tree
- [leetcode][tree] Same Tree
- LeetCode: Same Tree
- LeetCode Same Tree
- [Leetcode] Same Tree
- LeetCode : Same Tree
- [LeetCode] Same Tree
- leetcode 65: Same Tree
- Leetcode 100 Same Tree
- [leetcode] Same Tree
- [LeetCode]Same Tree
- [leetcode]Same Tree
- [Leetcode]Same Tree
- Leetcode: Same Tree
- [LeetCode] Same Tree
- LeetCode-Same Tree
- [leetcode] Same Tree
- LeetCode - Same Tree
- Android 拍照获取源图像
- 性能优化之Java(Android)代码优化
- Java学习笔记四——接口与内部类
- 哈希-4 Values whose Sum is 0
- split 分割 字符串(分隔符如:* ^ : | , .) 及注意点
- 【leetCode】Same Tree
- 可维护性与可扩展性的区别
- Unity安卓打包
- 基于V4L2驱动程序的USB摄像头Android(JNI)的编写(二)
- 二分查找算法
- 南邮 OJ 1900 闰年
- 【Qt OpenGL教程】20:蒙板
- Oracle 64bit 在redhat下内存如何调大
- ios随机数,and()、random()、arc4random()