补第十五周leetcode算法博客
100. Same Tree
Given two binary trees, 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.
源代码
/**
* 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) {
bool t;
if ((p != NULL && q == NULL) || (q != NULL && p == NULL)) {
return false;
} else if (p != NULL && q != NULL && q -> val != p -> val) {
return false;
} else {
if (p == NULL && q == NULL) {
return true;
} else if (p -> val == q -> val) {
return isSameTree(p -> left, q -> left) && isSameTree(p -> right, q -> right);
}
}
}
};
算法就是用前序遍历检查每个节点,注意叶子节点和部分中间节点的子节点为空的情况