PRoblem: 給一顆二叉樹,求這棵樹的左葉子節(jié)點(diǎn)之和。 Solution: dfs搜一下即可。 notes: 1. 默認(rèn)參數(shù)的應(yīng)用。 2. 要注意root可能為空,如果為空則不能方位它的左值,所以要處理這個(gè)異常。
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; }};新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注