Day 16 迎财神
坚持如此hard
玄之又玄,众妙之门
一、理论知识
回顾【深度】和【高度】的概念,现在主要还是写递归
2)
初识【回溯】
3)左叶子的明确定义:节点A的左孩子不为空,且左孩子的左右孩子都为空(说明是叶子节点),那么A节点的左孩子为左叶子节点
二、刷题学习
110. 平衡二叉树
实则在求高度。
/**
* 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 getheight(TreeNode* root){
//1
if(root==nullptr){
return 0;
}
//2
int left=getheight(root->left);
if(left==-1) return -1;
int right=getheight(root->right);
if(right==-1) return -1;
//3
int result=abs(left-right);
if(result>1) return -1;
else return max(left,right)+1;
}
bool isBalanced(TreeNode* root) {
int ans=getheight(root);
if(ans==-1) return false;
else return true;
}
};
257. 二叉树的所有路径
/**
* 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 traverse(TreeNode* root,vector<int>&path,vector<string>&result){
//mid
path.push_back(root->val);
//stop
if(root->left==nullptr && root->right==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);
return;
}
//left
if(root->left){
traverse(root->left,path,result);
path.pop_back();
}
if(root->right){
traverse(root->right,path,result);
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
vector<int> path;
if (root == NULL) return result;
traverse(root, path, result);
return result;
}
};
404. 左叶子之和
/**
* 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 sumOfLeftLeaves(TreeNode* root) {
//1
if(root==nullptr) return 0;
if (root->left == NULL && root->right== NULL) return 0;
int left= sumOfLeftLeaves(root->left);
if (root->left && !root->left->left && !root->left->right) { // 左子树就是一个左叶子的情况
left = root->left->val;
}
int right=sumOfLeftLeaves(root->right);
return left+right;
}
};
三、新年快乐
道可道,非常道