110. 平衡二叉树
C++:递归
class Solution {
public:
int height(TreeNode*root){
if(root==nullptr) return 0;
return max(height(root->left),height(root->right))+1;
}
bool isBalanced(TreeNode* root) {
if(root==nullptr) return true;
else return abs(height(root->left)-height(root->right))<=1
&& isBalanced(root->left) && isBalanced(root->right);
}
};
C++:递推
这个需判断height(root)>0即可。
class Solution {
public:
int height(TreeNode*root){
if(root==nullptr) return 0;
int heightLeft=height(root->left);
int heightRight=height(root->right);
if(heightLeft==-1) return-1;
if(heightRight==-1) return -1;
if(abs(heightRight-heightLeft)>1) return -1;
else return max(heightLeft,heightRight)+1;
}
bool isBalanced(TreeNode* root) {
if(root==nullptr) return true;
return height(root)>0;
}
};
C++:stack(上->下)
class Solution {
public:
int getheight(TreeNode*curr){
stack<TreeNode*> stk;
if(curr!=nullptr) stk.push(curr);
int depth=0;//记录深度
int result=0;
while(!stk.empty()){
TreeNode*node=stk.top();
if(node!=nullptr){
stk.pop();
stk.push(node);//中
stk.push(nullptr);
depth++;
if(node->right) stk.push(node->right);//右
if(node->left) stk.push(node->left);//左
}
else{
stk.pop();
node=stk.top();
stk.pop();
depth--;
}
result=result>depth?result:depth;
}
return result;
}
bool isBalanced(TreeNode* root) {
stack<TreeNode*> stk;
if(root==nullptr) return true;
stk.push(root);
while(!stk.empty()){
TreeNode*node=stk.top(); // 中
stk.pop();
if(abs(getheight(node->left)-getheight(node->right))>1){
return false;
}
if(node->right) stk.push(node->right); // 右(空节点不入栈)
if(node->left) stk.push(node->left); // 左(空节点不入栈)
}
return true;
}
};
257. 二叉树的所有路径
C++:回溯
class Solution {
public:
void backTracting(TreeNode*root,vector<string>&res,string temp){
temp+=to_string(root->val);
if(root->left==nullptr&&root->right==nullptr){
res.push_back(temp);
return;
}
if(root->left!=nullptr) backTracting(root->left,res,temp+"->");
if(root->right!=nullptr) backTracting(root->right,res,temp+"->");
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
string temp;
if(root==nullptr) return res;
backTracting(root,res,temp);
return res;
}
};
404. 左叶子之和
C++:递归
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(root==nullptr) return 0;
int leftValue=0;
if(root->left!=nullptr&&root->left->left==nullptr&&root->left->right==nullptr)
leftValue=root->left->val;
return leftValue+sumOfLeftLeaves(root->left)+sumOfLeftLeaves(root->right);
}
};
C++:stack
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(root==nullptr) return NULL;
stack<TreeNode*> stk;
stk.push(root);
int res=0;
while(!stk.empty()){
TreeNode* node=stk.top();
stk.pop();
if(node->left!=nullptr&&node->left->left==nullptr&&node->left->right==nullptr)
res+=node->left->val;
if (node->right) stk.push(node->right);
if (node->left) stk.push(node->left);
}
return res;
}
};