大纲
题目
地址
https://leetcode.com/problems/same-tree/description/
内容
Given the roots of two binary trees p and q, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
Example 1:
Input: p = [1,2,3], q = [1,2,3]
Output: true
Example 2:
Input: p = [1,2], q = [1,null,2]
Output: false
Example 3:
Input: p = [1,2,1], q = [1,1,2]
Output: false
Constraints:
- The number of nodes in both trees is in the range [0, 100].
- -104 <= Node.val <= 104
解题
这题就是要比较两个二叉树中节点数值以及结构是否一致。需要注意的是,不能通过判断两个节点的数值一致而返回true,而是要更多考虑不一致的情况,比如左右节点结构是否一致以及数值是否一致。能够完全确认两个节点相同的就是它们都是nullptr,即都遍历到最后一级,且之前都没遇到返回false的情况。
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if (p == nullptr && q == nullptr) return true;
if (p == nullptr || q == nullptr) return false;
if (p->val != q->val) return false;
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
};
代码地址
https://github.com/f304646673/leetcode/tree/main/100-Same-Tree
标签:right,TreeNode,val,Tree,nullptr,false,100,leetcode,left From: https://blog.csdn.net/breaksoftware/article/details/142110988