The sum of the left leaves
Title description: Calculate the sum of all left leaves of a given binary tree.
Please refer to LeetCode official website for example description.
Source: LeetCode
Link: https://leetcode-cn.com/problems/sum-of-left-leaves/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Solution 1: Recursion
First, if the root node root is null or there is only one node, it means that there is no leaf node, and 0 is directly returned;
Otherwise, add a recursive method recursive , there are 2 parameters, which are the left and right child nodes of the current node, flag is the identification of the left and right child nodes, the recursive process is as follows:
- Call the recursive method recursive , the parameters are root left and right child nodes, flag is the corresponding identifier;
- Determine if root in the recursive method null , then return;
- If root has no left and right child nodes and flag identified as the left child node, the value of root ;
- Otherwise, the recursive call recursive This , parameters are root left and right child nodes, Flag corresponding logo.
Finally, the return result is the sum of all left leaf nodes.
import com.kaesar.leetcode.TreeNode;
/**
* @Author: ck
* @Date: 2021/9/29 7:33 下午
*/
public class LeetCode_404 {
/**
* 叶子之和
*/
public static int result = 0;
public static int sumOfLeftLeaves(TreeNode root) {
if (root == null || (root.left == null && root.right == null)) {
return 0;
}
recursive(root.left, true);
recursive(root.right, false);
return result;
}
/**
* 递归方法
*
* @param root
* @param flag true表示是左子节点;false表示是右子节点
*/
public static void recursive(TreeNode root, boolean flag) {
if (root == null) {
return;
}
if (root.left == null && root.right == null && flag) {
result += root.val;
}
recursive(root.left, true);
recursive(root.right, false);
}
public static void main(String[] args) {
TreeNode root = new TreeNode(3);
root.left = new TreeNode(9);
root.right = new TreeNode(20);
root.right.left = new TreeNode(15);
root.right.right = new TreeNode(7);
// 期望返回值: 24
System.out.println(sumOfLeftLeaves(root));
}
}
[Daily Message] Lazy people wait for opportunities, hardworking people create opportunities.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。