题目
题目链接:
https://www.nowcoder.com/practice/405a9033800b403ba8b7b905bab0463d
思考
这是一道简单题,中序,前序,后序,层序遍历都可以
本答案利用层序遍历。BFS
参考答案Java
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型
*/
public int sumOfLeftLeaves (TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
TreeNode cur = root;
q.add(cur);
int ans = 0;
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode pop = q.poll();
if (pop.left != null) {
q.add(pop.left);
if (pop.left.left == null && pop.left.right == null) {
ans += pop.left.val;
}
}
if (pop.right != null) {
q.add(pop.right);
}
}
}
return ans;
}
}
参考答案Go
package main
import . "nc_tools"
/*
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型
*/
func sumOfLeftLeaves(root *TreeNode) int {
cur := root
q := []*TreeNode{}
q = append(q, cur)
ans := 0
for len(q) > 0 {
size := len(q)
qnew := []*TreeNode{}
for i := 0; i < size; i++ {
pop := q[i]
if pop.Left != nil {
qnew = append(qnew, pop.Left)
if pop.Left.Left ==nil && pop.Left.Right ==nil{
ans = ans+ pop.Left.Val
}
}
if pop.Right != nil {
qnew = append(qnew, pop.Right)
}
}
q = qnew
}
return ans
}
参考答案PHP
<?php
/*class TreeNode{
var $val;
var $left = NULL;
var $right = NULL;
function __construct($val){
$this->val = $val;
}
}*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型
*/
function sumOfLeftLeaves( $root )
{
$q = [$root];
$ans = 0;
while (count($q) > 0) {
$qnew = array();
$size = count($q);
for ($i = 0; $i < $size; $i++) {
$pop = $q[$i];
// $idx = $qindex[$i];
if ($pop->left != null) {
array_push($qnew, $pop->left);
if($pop->left->left ==null && $pop->left->right ==null){
$ans +=$pop->left->val;
}
}
if($pop->right!=null){
array_push($qnew, $pop->right);
}
}
$q = $qnew;
}
return $ans;
}