迭代三步走:
1. 确定递归函数的参数和返回值
2. 确定终止条件
3. 确定单层递归的逻辑
这里是用到了前序遍历来递归的方法。
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root==nullptr) return root;
swap(root->left,root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};
层序遍历(广度优先算法)
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
queue<TreeNode*>que;
if(root!=nullptr) que.push(root);
while(!que.empty()) {
int size=que.size();
while(size--) {
TreeNode* node=que.front();
que.pop();
swap(node->left,node->right);
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
}
return root;
}
};
递归真的好难
class Solution {
public:
bool compare(TreeNode* left, TreeNode* right) {
if(left==NULL&&right!=NULL) return false;
else if(left!=NULL&&right==NULL) return false;
else if(left==NULL&&right==NULL) return true;
else if(left->val!=right->val) return false;
bool outside=compare(left->left,right->right);
bool inside=compare(left->right,right->left);
return outside&&inside;
}
bool isSymmetric(TreeNode* root) {
if(root==nullptr) return true;
return compare(root->left,root->right);
}
};
自己想出来的双向队列方法,诶嘿
class Solution {
public:
bool isSymmetric(TreeNode* root) {
deque<TreeNode*>que;
if(root==nullptr) return true;
que.push_back(root->left);
que.push_back(root->right);
while(!que.empty()) {
TreeNode* frontNode=que.front();
TreeNode* backNode=que.back();
que.pop_front();
que.pop_back();
if(frontNode!=nullptr&&backNode==nullptr) return false;
else if(frontNode==nullptr&&backNode!=nullptr) return false;
else if(frontNode==nullptr&&backNode==nullptr) continue;
else if(frontNode->val!=backNode->val) return false;
que.push_front(frontNode->right);
que.push_front(frontNode->left);
que.push_back(backNode->left);
que.push_back(backNode->right);
}
return true;
}
};
这道题昨天用递归和层序遍历都写过一次了,再用递归写一次
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==nullptr) return 0;
return max(maxDepth(root->left),maxDepth(root->right))+1;
}
};
昨天觉得不能用递归,然后看题解发现是可以的。
求二叉树的最小深度和求二叉树的最大深度的差别主要在于处理左右孩子不为空的逻辑。
这题的意思就是求根节点到叶子结点的最小深度,叶子节点要求左孩子和右孩子都为空,所以不能出现一边为空一边不为空的情况,如果出现了,这时候就要继续往不为空的那边遍历。
class Solution {
public:
int getDepth(TreeNode* node) {
if(node==nullptr) return 0;
int leftDepth = getDepth(node->left);
int rightDepth = getDepth(node->right);
if (node->left == NULL && node->right != NULL) {
return 1 + rightDepth;
}
// 当一个右子树为空,左不为空,这时并不是最低点
if (node->left != NULL && node->right == NULL) {
return 1 + leftDepth;
}
int result = 1 + min(leftDepth, rightDepth);
return result;
}
int minDepth(TreeNode* root) {
return getDepth(root);
}
};
这样更好理解。
class Solution {
public:
int minDepth(TreeNode* root) {
if(root==nullptr) return 0;
else if(root->left ==nullptr) return minDepth(root->right)+1;
else if(root->right ==nullptr) return minDepth(root->left)+1;
else return min(minDepth(root->left),minDepth(root->right))+1;
}
};
不想做二叉树了,,时间好赶呐
感觉递归就是要只看当下要做啥,把树的结构只看成根节点、左节点、右节点,别的不用考虑了,留给下一次再考虑,对我来说还是有点困难。