题目1(二叉树中和为某一值的路径)
bool hasPathSum(TreeNode* root, int sum) {
// write code here
if(root==NULL)
return false;
if(root->left==NULL&&root->right==NULL&&sum-root->val==0)
return true;
return hasPathSum(root->left, sum-root->val)||hasPathSum(root->right,sum-root->val);
}
学习这种将sum值传下去,递归return相减的方法
题目2(对称的二叉树)
bool ismirrow(TreeNode * t1,TreeNode *t2){
if(t1==NULL&&t2==NULL)
return true;
if(t1==NULL||t2==NULL||t1->val!=t2->val)
return false;
return ismirrow(t1->left, t2->right)&&ismirrow(t1->right, t2->left);
//唔~好像有丢丢悟了,这种方法最终才返回最终的结果,如果中途遇到false的情况就会一直返回给最开始,
//因为&的关系有记忆性,会记忆每一个false
}
bool isSymmetrical(TreeNode* pRoot) {
return ismirrow(pRoot,pRoot);
}
这道题的求解很巧妙,最开始我想的是先求其镜像树,然后再依次遍历有点像入栈的意思,以相同的顺序遍历查看是否每一个位置是否相同(还没有具体实现,估计思路应该差不多,当时没有想到递归&&flase的值可以永远传递这个思想,有时间可以试一下)
题目3(二叉树的镜像)
TreeNode* Mirror(TreeNode* pRoot) {
// write code here
if(pRoot==NULL)
return pRoot;
TreeNode *head=new TreeNode(pRoot->val);
head->left=Mirror(pRoot->right);
head->right=Mirror(pRoot->left);
return head;
}
这道题主要是记得创建一个新节点,然后对其左孩子和有孩子分别递归赋值,最后返回的思想
题目4(合并二叉树)
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
// write code here
if(t1==NULL)
return t2;
if(t2==NULL)
return t1;
TreeNode *head=new TreeNode(t1->val+t2->val);
head->left=mergeTrees(t1->left, t2->left);
head->right=mergeTrees(t1->right, t2->right);
return head;
}
这道题的思想与上一题的差不多都是创建新节点递归赋值返回~就是刚开始的判断有丢丢区别
有关基本二叉树的创建查看往期博客