?LeetCode刷題實(shí)戰(zhàn)404:左葉子之和
Given?the?root?of?a?binary?tree,?return?the?sum?of?all?left?leaves.
示例
? ? ?3
???/ \
??9? 20
????/ \
???15? 7
在這個(gè)二叉樹中,有兩個(gè)左葉子,分別是 9 和 15,所以返回 24
解題
class?Solution?{
public:
????void helper(TreeNode* root,int& sum,bool is_left){
????????if(root==NULL){//空節(jié)點(diǎn)返回
????????????return;
????????}
????????//為葉子結(jié)點(diǎn)
????????if(root->left==NULL&&root->right==NULL){
????????????if(is_left){//為左結(jié)點(diǎn)
????????????????sum+=root->val;
????????????}
????????????return;
????????}
????????helper(root->left,sum,true);//遍歷左子樹,標(biāo)識(shí)是左子樹
????????helper(root->right,sum,false);//遍歷右子樹,標(biāo)識(shí)不是左子樹
????}
????int sumOfLeftLeaves(TreeNode* root) {
??????//處理特殊的情形
????????if(root==NULL||(root->left==NULL&&root->right==NULL)){
????????????return?0;
????????}
????????int sum=0;
????????helper(root,sum,true);
????????return?sum;
????}
};
LeetCode1-400題匯總,希望對(duì)你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)401:二進(jìn)制手表
LeetCode刷題實(shí)戰(zhàn)402:移掉 K 位數(shù)字
LeetCode刷題實(shí)戰(zhàn)403: 青蛙過河
