代码随想录刷题03.01
二叉树相关操作4
LeetCode题目
解题思路
1.在递归体代码中左、右、中三者代表的代码含义不同:
1)左、右:表示如何向下一层传递以及下一层如何返回;
2)中:表示对递归体代码中的所有变量具体的操作执行。
2.在左、右向下传递以及向上返回时,可以采用剪枝操作。
代码过程
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int travel(TreeNode*root)
{
if(root==nullptr)return 0;
else{
int lefthight=travel(root->left);
if(lefthight==-1)return -1;
int righthight=travel(root->right);
if(righthight==-1)return -1;
int result;
if(abs(lefthight-righthight)>1)result=-1;
else
result=max(lefthight,righthight)+1;
return result;
}
}
bool isBalanced(TreeNode* root) {
int hight=travel(root);
if(hight==-1)return false;
else return true;
}
};
LeetCode题目
解题思路
1.左、右:表示上一层和下一层之间的传递(传入和返回);
中:表示具体操作执行;
2.涉及到分叉时,要注意数据能否在两条岔路上互通:
1)添加引用&;
2)num=travel(……,num);
3)int travel(TreeNode*root)
int leftnum……;//单路共通;
int rightnum……;//单路共通;
int num=leftnum+rightnum;//双路共通;
return num;
3.本题的思路:后序遍历到最后的节点,判断是否是符合题意的左子节点,然后累加。
代码过程
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void travel(TreeNode*root,int& sum){
if(root==nullptr)return;
if(root->left==nullptr&&root->right==nullptr)
return;
travel(root->left,sum);
travel(root->right,sum);
if(root->left!=nullptr&&root->left->left==nullptr&&root->left->right==nullptr)
sum+=root->left->val;
}
int sumOfLeftLeaves(TreeNode* root) {
int sum=0;
travel(root,sum);
return sum;
}
};
LeetCode题目
解题思路
1.本题思路:采用前序,从根部向下遍历,在完成一条路径后,采用回溯退回:
travel(……)表示向下遍历的动力;path.pop_back()表示遍历到底后向回退的动力。
2.小小的纠正:递归终止条件的书写主要结合题意,和前中后序遍历关系不是很大。
另外,要注意剪枝(但剪枝不是递归的终止条件)。
代码过程
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void travel(TreeNode*root,vector<int>&path,vector<string>&result){
path.push_back(root->val);
if(root->right==nullptr&&root->left==nullptr){
string spath;
for(int i=0;i<path.size()-1;i++)
{
spath+=to_string(path[i]);
spath+="->";
}
spath+=to_string(path[path.size()-1]);
result.push_back(spath);
}
if(root->left){
travel(root->left,path,result);
path.pop_back();
}
if(root->right){
travel(root->right,path,result);
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<int>path;
vector<string>result;
travel(root,path,result);
return result;
}
};