本文主要是介绍leetcode oj Sum of Left Leaves,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、问题描述:
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.二、思路:
先序遍历二叉树,判断结点是否为左叶子结点:
三、实现代码:
public class Solution {public int sumOfLeftLeaves(TreeNode root) {if (root== null) {return 0;}if (root.left != null && root.left.right == null && root.left.left == null) {return root.left.val + sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);}return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);}
}
这篇关于leetcode oj Sum of Left Leaves的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!