题目
/**
* 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 == NULL && q == NULL) { //结束条件,要注意空指针
return true;
}else if((q == NULL && p != NULL )||(q != NULL && p == NULL)){
return false;
}
if(p->val != q->val) return false;
int a = isSameTree(p->left,q->left); //判断该层的左子树是否相等
int b = isSameTree(p->right,q->right);//判断该层的右子树是否相等
if(a == 1 && b == 1){ //如果左子树和右子树都相等
return true;
}else{
return false;
}
}
};
本题运用递归三部曲:
1.找整个递归的终止条件:递归应该在什么时候结束?
2.找返回值:应该给上一级返回什么信息?
3.本级递归应该做什么:在这一级递归中,应该完成什么任务?
出现的错误
编译出错
Line 24: Char 5: fatal error: control may reach end of non-void function [-Wreturn-type]
}
^
1 error generated.
出现以上错误的代码
/**
* 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 == NULL && q == NULL) {
return true;
}else if((q == NULL && p != NULL )||(q != NULL && p == NULL)){
return false;
}
if(p->val != q->val) return false;
int a = isSameTree(p->left,q->left);
int b = isSameTree(p->right,q->right);
if(a == 1 && b == 1){
return true;
}//此处不同
}
};
原因:所有return都在if条件语句里,在不同处加else并且在里面加return就可以通过
Leetcode101.对称二叉树
/**
* 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 isSymmetric(TreeNode* root) {
if(root == NULL) return true;
if(is_same(root->left,root->right)){
return true;
}else{
return false;
}
}
private:
bool is_same(TreeNode * lchild,TreeNode *rchild){
if(lchild == NULL && rchild == NULL){
return true;
}else if((lchild == NULL && rchild != NULL) || (lchild != NULL && rchild == NULL)){
return false;
}
if(lchild->val != rchild->val){
return false;
}
int a = is_same(lchild->left,rchild->right );
int b = is_same(lchild->right, rchild->left);
if(a == 1 && b == 1){
return true;
}else{
return false;
}
}
};
/**
* 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:
vector<vector<int>> vec;
vector<vector<int>> levelOrder(TreeNode* root) {
level_binary(root,0);
return vec;
}
void level_binary(TreeNode * root,int level){
if(root == NULL){ //递归终止条件
return ;
}
if(vec.size() == level) vec.resize(level + 1);
vec[level].push_back(root->val);
level_binary(root->left,level + 1);
level_binary(root->right,level + 1);
}
};