110. 平衡二叉树 - 力扣(LeetCode)
思路:用局部变量接收每个结点的值
重点:取左右子树最大的高度,后序遍历求高度
class Solution {
public:
int fun(TreeNode* root){
if(root==NULL){
return 0;
}
int a=fun(root->left);
int b=fun(root->right);
if(a==-1||b==-1||abs(a-b)>1){
return -1;
}
return max(a,b)+1;
}
bool isBalanced(TreeNode* root) {
return fun(root)!=-1;
}
};
257. 二叉树的所有路径 - 力扣(LeetCode)
思路:中序遍历,回溯遍历出每一条路径
重点:注意字符串拼接处有回溯逻辑
class Solution {
public:
void fun(TreeNode* root,string path,vector<string>& ans){
path+=to_string(root->val);
if(root->left==nullptr&&root->right==nullptr){
ans.push_back(path);
return;
}
if(root->left) fun(root->left,path+"->",ans);//回溯逻辑
if(root->right) fun(root->right,path+"->",ans);
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string>ans;
string path;
if(root==nullptr){
return {};
}
fun(root,path,ans);
return ans;
}
};
404. 左叶子之和 - 力扣(LeetCode)
思路:判断当前左子树是否为叶子结点,按照后序遍历
递归法
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(root==nullptr){
return 0;
}
int ans=0;
if(root->left&&root->left->left==nullptr&&root->left->right==nullptr){
ans=root->left->val;
}
return ans+sumOfLeftLeaves(root->left)+sumOfLeftLeaves(root->right);
}
};
迭代法
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;
}
};
222. 完全二叉树的节点个数 - 力扣(LeetCode)
思路:遍历二叉树,统计结点个数
class Solution {
public:
int countNodes(TreeNode* root) {
if(root==NULL){
return 0;
}
return 1+countNodes(root->left)+countNodes(root->right);
}
};
总结
后序遍历求高度,前序遍历求深度,ans+sumOfLeftLeaves(root->left)+sumOfLeftLeaves(root->right);统计结点的逻辑