100. Same Tree 树是否相同

来源:互联网 发布:开淘宝网店怎样找货源 编辑:程序博客网 时间:2024/06/05 15:17

https://leetcode.com/problems/same-tree/


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.


注意这题其实跟 101. Symmetric Tree 对称树 一样的做法。只不过对称树判断自己跟自己的镜像是否相等。


/** * 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) {if (p ==NULL && q == NULL){return true;}else if (p == NULL || q == NULL){return false;}else if (p->val == q->val){return isSameTree(p->left, q->left)&isSameTree(p->right, q->right);//注意这里return 递归,而不是直接return true}else{return false;}}};


0 0
原创粉丝点击