首页 > 编程语言 > 详细

408算法练习——左叶子之和

时间:2021-08-14 00:09:43      阅读:24      评论:0      收藏:0      [点我收藏+]

左叶子之和

问题链接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 }

 

408算法练习——左叶子之和

原文:https://www.cnblogs.com/zyq79434/p/15139031.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!