写在前面
刚开始写博客,希望大家多多支持哈,我的个人动态博客网站链接:flamsteed,在CSDN上面同步更新。
最近做了一些题目,发现dfs竟有些生疏了,所以就到leetcode的dfs分类下面刷题,然后发现二叉树也生疏了=.= 做了几题,感觉值得整理一下,可以加深对二叉树的理解与应用。
另外关于所有二叉树的定义如下:
//Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
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.
题目大意:判断输入的两棵二叉树是否完全相等
解法:虽然题目很简单,但是本着练习的目的,还是要认真做一下,这里可以有两种做法,recursion和iteration。
(一)recursion:
递归解法思路很简单,递归判断p->left和q->left,p->right和q->right是否是相等的子树。
代码:
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p && q){
if(p->val==q->val){
return ((isSameTree(p->left,q->left))&&(isSameTree(p->right,q->right)));
}
else return false;
}
else if(p==NULL && q==NULL){
return true;
}
else return false;
}
};
(二)iteration:
迭代代码量大一些,用循环代替了函数的递归调用,用队列(vector数组也可以)暂存满足条件的左右孩子。
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if (p == NULL && q == NULL) return true;
if (p == NULL || q == NULL) return false;
TreeNode *curp = NULL, *curq = NULL;
queue<TreeNode *>qp;
queue<TreeNode *>qq;
qp.push(p);