• 【LeetCode-树】左叶子之和


    题目描述

    计算给定二叉树的所有左叶子之和。
    示例:

        3
       / 
      9  20
        /  
       15   7
    
    在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
    

    题目链接: https://leetcode-cn.com/problems/sum-of-left-leaves/

    思路

    一棵树的所有左叶子之和就是这棵树左子树的左叶子+右子树的左叶子。只有是左叶子才加进结果里,判断一个节点是否是左叶子的方法是根据该节点的父节点来判断:如果该节点是父节点的左子节点并且该节点没有孩子节点,那么该节点就是左叶子。代码如下:

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int sumOfLeftLeaves(TreeNode* root) {
            if(root==nullptr) return 0;
            if(root->left!=nullptr && root->left->left==nullptr && root->left->right==nullptr){
                return root->left->val + sumOfLeftLeaves(root->right);
            }
            return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
        }
    };
    

    也可以这样写

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int sumOfLeftLeaves(TreeNode* root) {
            ans = 0;
            doSum(root);
            return ans;
        }
    
        void doSum(TreeNode* root){
            if(root==nullptr) return;
            if(root->left!=nullptr && root->left->left==nullptr && root->left->right==nullptr){
                ans += root->left->val;
                //return;  // 这里不能 return
            }
    
            doSum(root->left);
            doSum(root->right);
        }
    
    private:
        int ans;
    };
    
    • 时间复杂度:O(n)
      n为树中节点的个数,因为要把所有的节点遍历一遍。
    • 空间复杂度:O(h)
      h为树的高度,因为使用递归。
  • 相关阅读:
    UITableView加载显示更多内容
    UITableView  折叠效果
    40个GitHub上最受欢迎的iOS开源项目
    oc中的block使用心得
    iOS CGRectContainsPoint的用法
    ios NSComparator 三种枚举类型
    错误提示 Unsupported compiler 'com.apple.compilers.llvmgcc42' selected for architecture 'i386'
    IOS 第三方库之-MBProgressHUD的使用详解
    ios 测试工程是否内存泄漏
    单双击手势
  • 原文地址:https://www.cnblogs.com/flix/p/12694432.html
Copyright © 2020-2023  润新知