110.平衡二叉树
思路:求高度,后序遍历(求高度)
代码如下
class Solution {
public:
int gethight(TreeNode*node){
if(node==NULL)
return 0;
int lefthight=gethight(node->left);
if(lefthight==-1)
return -1;
int righthigrt=gethight(node->right);
if(righthigrt==-1) return -1;
return abs(lefthight-righthigrt)>1?-1 :1+max(lefthight,righthigrt);
}
bool isBalanced(TreeNode* root) {
return gethight(root)==-1?false:true;
}
};
257. 二叉树的所有路径
思路:前序遍历
代码如下:
class Solution {
private:
void traversal(TreeNode*cur ,string path,vector<string>&result){
path=path+to_string(cur->val);
if(cur->left==NULL&&cur->right==NULL){
result.push_back(path);
return ;
}
if(cur->left){
path+="->";
traversal(cur->left,path,result);
path.pop_back();
path.pop_back();
}
if(cur->right){
path+="->";
traversal(cur->right,path,result);
path.pop_back();
path.pop_back();
}
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string>result;
string path;
if(root==NULL)
return result;
traversal(root,path,result);
return result;
}
};
迭代法
模拟递归需要一个栈,同时还需要一个栈来存放对应的遍历路径。
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
stack<TreeNode*> treeSt;
stack<string> pathst;
vector<string> result;
if(root==NULL) return result;
treeSt.push(root);
pathst.push(to_string(root->val));
while(!treeSt.empty()){
TreeNode* node=treeSt.top();
treeSt.pop();
string path = pathst.top();pathst.pop(); // 取出该节点对应的路径
if (node->left == NULL && node->right == NULL) { // 遇到叶子节点
result.push_back(path);
}
if (node->right) { // 右
treeSt.push(node->right);
pathst.push(path + "->" + to_string(node->right->val));
}
if (node->left) { // 左
treeSt.push(node->left);
pathst.push(path + "->" + to_string(node->left->val));
}
}
return result;
}
};
404.左叶子之和
递归法:判断当前节点是不是左叶子是无法判断的,必须要通过节点的父节点来判断其左孩子是不是左叶子
代码如下:
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(root==NULL)
return 0;
if(root->left==NULL&&root->right==NULL)
return 0;
int leftvalue=sumOfLeftLeaves(root->left);
if(root->left&&!root->left->left&&!root->left->right){
leftvalue=root->left->val;
}
int rightvalue=sumOfLeftLeaves(root->right);
int sum=leftvalue+rightvalue;
return sum;
}
};
迭代法:
把左叶子节点统计出来,使用中后序都可以
代码如下
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
stack<TreeNode*> st;
if (root == NULL) return 0;
st.push(root);
int result = 0;
while (!st.empty()) {
TreeNode* node = st.top();
st.pop();
if (node->left != NULL && node->left->left == NULL && node->left->right == NULL) {
result += node->left->val;
}
if (node->right) st.push(node->right);
if (node->left) st.push(node->left);
}
return result;
}
};