Problem:
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.
题意是给出两个二叉树,然后写一个函数检查这两棵树是否是相等的。其中相等是指结构一致并且每个节点上的值val都相等。这题比较简单,用递归的话代码会比较清晰,也可以用循环迭代。递归的话,首先得确定终止的条件。其中终止的条件有两种,一种是递归到最后一层的终止条件 if(!p && !q),表示p和q最后同时指向了null。一种是不相等的终止条件,其中一个是if(!p || !q),由于第一个if(!p && !q)不满足条件才能执行这个条件,所以p和q不能同时指向null,这明显是结构不等的。还有一个不等的条件是val比较 && p左子树等于q左子树 && p右子树等于q右子树。代码如下:
运行结果:3ms
Code:
/**
* 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 && !q) {
return true;
}
//不同时等于null,不等。
if (!p || !q) {
return false;
}
return (p -> val == q -> val) && isSameTree(p -> left, q -> left) && isSameTree(p -> right, q -> right);
}
};
以下是非递归版本的,用栈来实现,时间复杂度和空间复杂度都为O(n),原理类似前序遍历两个二叉树:
bool isSameTree(TreeNode *p, TreeNode *q) {
stack<TreeNode *> s;
s.push(p);
s.push(q);
while (!s.empty()) {
p = s.top();
s.pop();
q = s.top();
s.pop();
if (!p && !q) {
continue;
}
if (!p || !q || p -> val != q -> val) {
return false;
}
s.push(p -> left);
s.push(q -> left);
s.push(p -> right);
s.push(q -> right);
}
return true;
}