leetcode 404 Sum of Left Leaves

    xiaoxiao2021-03-26  27

    Problem: 给一颗二叉树,求这棵树的左叶子节点之和。 Solution: dfs搜一下即可。 notes: 1. 默认参数的应用。 2. 要注意root可能为空,如果为空则不能方位它的左值,所以要处理这个异常。

    class Solution { public: int sumOfLeftLeaves(TreeNode* root, bool isLeft = false) { int ans = 0; if(!root) return 0; if(isLeft && !root->left && !root->right) ans += root->val; else { ans += sumOfLeftLeaves(root->left, true); ans += sumOfLeftLeaves(root->right); } return ans; } };
    转载请注明原文地址: https://ju.6miu.com/read-662770.html

    最新回复(0)