0. 题目
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.
1. c++版本
思想1, 这个方法是用迭代的思想,只有有一点不相等,就直接返回 false
bool isSameTree(TreeNode* p, TreeNode* q) {
if ((p && !q) || (!p && q))
return false;
if (!p && !q)
return true;
if (p && q) {
if (p->val != q->val)
return false;
if (!isSameTree(p->left, q->left))
return false;
if (!isSameTree(p->right, q->right))
return false;
}
return true;
}
升级版本,其实就是中序遍历, 不过中序遍历忘记了……
void preOrder(TreeNode* p, vector<int>& result) {
if (p) {
result.push_back(p->val);
preOrder(p->left, result);
preOrder(p->right, result);
}
result.push_back(INT_MIN);
}
bool isSameTree(TreeNode* p, TreeNode* q) {
vector<int> result1, result2;
preOrder(p,result1 );
preOrder(q, result2);
if (result1 == result2)
return true;
return false;
}
2. python版本
TODO
网友评论