本文主要是介绍[LeetCode] 404. Sum of Left Leaves,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题:https://leetcode.com/problems/sum-of-left-leaves/description/
题目
Find the sum of all left leaves in a given binary tree.
Example:
3/ \9 20/ \15 7There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
题目大意
求所有左叶子的和。其中左叶子的定义为:1.为叶子;2.为某结点的左子树。
思路
先序遍历,若一个结点为左子树为 叶子,那么累加。
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/
class Solution {int tsum = 0;public void dfs(TreeNode root){if(root == null)return;if(root.left != null && root.left.left == null && root.left.right == null)tsum += root.left.val;dfs(root.left);dfs(root.right);}public int sumOfLeftLeaves(TreeNode root) {dfs(root);return tsum;}
}
这篇关于[LeetCode] 404. Sum of Left Leaves的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!