【c++刷题笔记-二叉树】day15: 110.平衡二叉树 、257. 二叉树的所有路径 、 404.左叶子之和、 222.完全二叉树的节点个数

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);统计结点的逻辑

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值