問題:
Find the sum of all left leaves in a given binary tree.
Example:
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
大意:
計算一個二叉樹中所有左葉子節(jié)點的和
例子:
在這個二叉樹中有兩個左葉子節(jié)點猜扮,分別為9和15辱匿。因此返回24。
思路:
從思路來說也沒有什么特別的地方,就是去做判斷距芬,細(xì)心一點不要有漏洞就好。
大體上分為判斷有沒有左節(jié)點和有沒有右節(jié)點赃磨。如果有左節(jié)點立由,看左節(jié)點有沒有子節(jié)點轧钓,沒有(即左葉子節(jié)點)則直接用其值去加,有則繼續(xù)對左節(jié)點遞歸锐膜。如果有右節(jié)點毕箍,且右節(jié)點有子節(jié)點,則對右節(jié)點遞歸道盏,否則不管是沒有右節(jié)點還是右節(jié)點沒有子節(jié)點(即右葉子節(jié)點)都直接看做加0而柑。需要注意的是如果本身節(jié)點自己是null,要返回0荷逞。另外如果只有根節(jié)點自己媒咳,也要返回0,因為題目說的是左葉子節(jié)點种远,根節(jié)點是不算的涩澡。最后要注意的就是在判斷所有節(jié)點的子節(jié)點或者值之前,要對該節(jié)點本身是否為null做出判斷坠敷,否則會有錯誤的妙同。
代碼(Java):
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) return 0;
else if (root.left == null && root.right == null) return 0;
else {
return ((root.left != null && root.left.left == null && root.left.right == null) ? root.left.val : sumOfLeftLeaves(root.left)) + ((root.right != null && (root.right.left != null || root.right.right != null)) ? sumOfLeftLeaves(root.right) : 0);
}
}
}
代碼(C++)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (root == nullptr) {
return 0;
}
if (root->left != nullptr) {
if (root->left->left == nullptr && root->left->right == nullptr) {
return root->left->val + sumOfLeftLeaves(root->right);
} else {
return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
}
}
if (root->right != nullptr){
return sumOfLeftLeaves(root->right);
}
return 0;
}
};
合集:https://github.com/Cloudox/LeetCode-Record