一、今日刷题
1. 第七部分:二叉树 – 404. 左叶子之和
给定二叉树的根节点 root ,返回所有左叶子之和。
答案代码:
自己的思路,参考题解的代码:做题时意识到了要想判断某节点是否为左叶子,必须要通过节点的父节点来判断其左孩子是不是左叶子。如果该节点的左节点不为空,该节点的左节点的左节点为空,该节点的左节点的右节点为空,则找到了一个左叶子。
但在写代码时,把 sum 作为了函数的一个参数,像题解这样写在方法外是很好的。
package BinaryTree;
/**
* @author: LYZ
* @date: 2022/2/27 14:28
* @description: 404. 左叶子之和
*/
public class SumOfLeftLeaves {
public static void main(String[] args) {
TreeNode p = new TreeNode(1, new TreeNode(1, new TreeNode(2), new TreeNode(3)), new TreeNode(6));
SumOfLeftLeaves sumOfLeftLeaves = new SumOfLeftLeaves();
int ans = sumOfLeftLeaves.sumOfLeftLeaves(p);
System.out.println(ans);
}
public int sumOfLeftLeaves(TreeNode root) {
countSum(root);
return sum;
}
int sum = 0;
public void countSum(TreeNode root) {
if (root == null) {
return;
}
if (root.left != null) {
if (root.left.left == null && root.left.right == null) {
sum += root.left.val;
}
}
countSum(root.left);
countSum(root.right);
}
}
明天就开学了,希望能保持每天刷题写博客的节奏,并且在这里记录一下课内遇到的问题。