題目描述: Find the sum of all left leaves in a given binary tree. 例子: 解題思路: 用遞推對二叉樹進行遍歷,判斷是否為末枝的左子葉,然後將所有的末枝的左子葉相加(不要忘了考慮空指針的情況) 代碼: 解題收穫: 對於C語言鏈表的使用還是有些不 ...
題目描述:
Find the sum of all left leaves in a given binary tree.
例子:
3 / \ 9 20 / \ 15 7 There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
解題思路:
用遞推對二叉樹進行遍歷,判斷是否為末枝的左子葉,然後將所有的末枝的左子葉相加(不要忘了考慮空指針的情況)
代碼:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * struct TreeNode *left; 6 * struct TreeNode *right; 7 * }; 8 */ 9 int sumOfLeftLeaves(struct TreeNode* root) { 10 if (!root) 11 //輸入為空指針時 12 { 13 return 0; 14 } 15 int leftLeavesSum = 0; 16 if (root->left) 17 { 18 if (!root->left->left && !root->left->right) 19 //結束的條件也就是末枝的左子葉時 20 { 21 leftLeavesSum += root->left->val; 22 } 23 else 24 { 25 leftLeavesSum += sumOfLeftLeaves(root->left); 26 } 27 } 28 if (root->right) 29 { 30 leftLeavesSum += sumOfLeftLeaves(root->right); 31 } 32 return leftLeavesSum; 33 }
解題收穫:
對於C語言鏈表的使用還是有些不夠熟練,還需要多加練習。