JAVA版本
解法一:
递归
本题的递归的思路是,用后续遍历的方式,由上到下,把左右节点的值记录在中间的节点当中,由上到下把值加起来就得到了最终的结果,因为本题要找的是左叶子,左叶子的判断方法有点不同,注意本题当中递归的判断条件。
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if(root == null) {
return 0;
}
if (root.left ==null && root.right == null){
return 0;
}
int midvalue =0;
if (root.left != null &&root.left.left == null && root.left.right ==null) {
midvalue = root.left.val;
}
int leftvalue = sumOfLeftLeaves(root.left);
int rightvalue = sumOfLeftLeaves(root.right);
int result= midvalue +rightvalue+leftvalue;
return result;
}
}
解法二:
使用迭代的解法,一个结点一个结点的进行判断。注意左右结点的判空操作。
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if(root == null) {
return 0;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
int result =0;
while(!stack.isEmpty()){
TreeNode temp = stack.pop();
if (temp.left != null && temp.left.left == null && temp.left.right == null) {
result += temp.left.val;
}
if (temp.right != null){
stack.push(temp.right);
}
if(temp.left != null){
stack.push(temp.left);
}
}
return result;
}
}