左叶子之和
问题链接:https://leetcode-cn.com/problems/sum-of-left-leaves/
一、问题描述
计算给定二叉树的所有左叶子之和。
示例:
3
/ \
9 20
/ \
15 7
在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
二、问题分析
最先想到深度优先遍历,遍历过程中对左叶子节点进行识别然后累计结果即可
三、代码
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode() {} 8 * TreeNode(int val) { this.val = val; } 9 * TreeNode(int val, TreeNode left, TreeNode right) { 10 * this.val = val; 11 * this.left = left; 12 * this.right = right; 13 * } 14 * } 15 */ 16 class Solution { 17 public int sumOfLeftLeaves(TreeNode root) { 18 if(isleaf(root)){ 19 return 0; 20 } 21 return dfs(root); 22 } 23 public int dfs(TreeNode root){ 24 int ans = 0; 25 if(root.left != null){ 26 ans += isleaf(root.left)?root.left.val:dfs(root.left); 27 } 28 if(root.right !=null && !isleaf(root.right)){ 29 ans += dfs(root.right); 30 } 31 return ans; 32 } 33 public boolean isleaf(TreeNode node){ 34 return node.left == null && node.right == null; 35 } 36 }
原文:https://www.cnblogs.com/zyq79434/p/15139031.html